Modern JavaScript Web Development Cookbook
上QQ阅读APP看书,第一时间看更新

Padding strings 

You can pad a string to a given length by adding repeated strings either at the left or at the right of the original text by using .padStart(...) and .padEnd(...):

"Hello".padStart(12);       // "       Hello"
"Hello".padStart(12,"XYZ"); // "XYZXYZXHello"
"Hello".padStart(3); // "Hello"; no effect here

"Hello".padEnd(12); // "Hello "
"Hello".padEnd(12,"XYZ"); // "HelloXYZXYZX"
"Hello".padEnd(4); // "Hello"; no effect here either

Among possible uses, you may pad a number with zeroes to the left. We have to transform the number into a string because the padding methods are only available for strings:

let padded = String(229.6).padStart(12, "0"); // "0000000229.6"
The reason for using   padStart  and   padEnd  instead of   padLeft  and   padRight  has to do with left-to-right and right-to-left languages. It was felt that start and end were not ambiguous, while left and right would be. For example, in Hebrew, the start of a string is printed at the right and its end is to the left.