December 2018
Intermediate to advanced
642 pages
15h 5m
English
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"
Read now
Unlock full access