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 ";

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 ""

// outputs "Hello World Hello World "
Trimming Strings in Javascript
Padding Strings in Javascript