Repeating or Padding Strings in JavaScript

October 13th, 2008

Here’s a nice trick for repeat a string a given number of times. Let’s say you want to create string with the characters “ABC” repeated 5 times. The most straightforward approach that you could use 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 could also have avoided all the 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 empty strings (or undefined slots) and used “ABC” as the delimiter:

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 be used for padding a string with a given string, repeated a given number of times:

Add a Comment