Repeating or Padding Strings in JavaScript
Here’s a nice trick for repeating a string a given number of times.
Let’s say you want to create a string with the characters “ABC” repeated 5 times. The most straightforward approach that you could take is to set up a for loop to append “ABC” to a string 5 times:
var s = "";
for (var i = 0; i < 5; i++) {
s += "ABC";
}
alert(s); // Gives you "ABCABCABCABCABC"
You can avoid repeated concatenation by using an intermediary Array:
var arr = [];
for (var i = 0; i < 5; i++) {
arr.push("ABC");
}
alert(arr.join("")); // Gives you "ABCABCABCABCABC"
We populated an array with 5 instances of the string “ABC” and then joined the array items into a single string with an empty string as the delimiter (i.e. no delimiter). What may not be immediately obvious is that we could have as well done the opposite and populate the array with 5 + 1 = 6 empty strings and used “ABC” as the delimiter:
var arr = [];
for (var i = 0; i < 6; i++) {
arr.push("");
}
alert(arr.join("ABC")); // Gives you "ABCABCABCABCABC"
Or equivalently:
var arr = new Array(6);
alert(arr.join("ABC")); // Gives you "ABCABCABCABCABC"
Or in short form:
alert((new Array(6)).join("ABC")); // Gives you "ABCABCABCABCABC"
This can also be used for padding a string with a given string, repeated a given number of times:
/**
* Left-pad a number with zeros so that it's at least the given
* number of characters long
* @param n The number to pad
* @param len The desired length
*/
function leftPad(n, len) {
return (new Array(len - String(n).length + 1)).join("0").concat(n);
}
alert(leftPad(42, 6)); // Gives "000042"