Repeating Strings in Javascript

Sometimes it is required to keep repeating a string for a specific number of times. You may be probably looking to fill out a container element, without typing it - lorem ipsum text for example.

Earlier you could do it with a loop. But now, ES6 has brought forward an inbuilt function to do the same.

The repeat Method

The repeat method concatenates a given string for a specific number of times, and returns it.

var str = "Hello World ";

var new_str = str.repeat(3);

// outputs "Hello World Hello World Hello World ";
console.log(str);

In case the string is repeated for a value of 0, it will return a blank string. Decimals will be converted to integers.

var str = "Hello World ";

// outputs ""
console.log(str.repeat(0));

// outputs "Hello World Hello World "
console.log(str.repeat(2.7));
Trimming Strings in Javascript
Padding Strings in Javascript