Repeat a String for Multiple Times in Javascript

A string can be repeated for a given number of times using the repeat() method. This concatenates the 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));

Leave a Reply

Your email address will not be published. Required fields are marked *