JavaScript Strings Repeat a String

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

6

This can be done using the .repeat() method:

"abc".repeat(3);  // Returns "abcabcabc"
"abc".repeat(0);  // Returns ""
"abc".repeat(-1); // Throws a RangeError
6

In the general case, this should be done using a correct polyfill for the ES6 String.prototype.repeat() method. Otherwise, the idiom new Array(n + 1).join(myString) can repeat n times the string myString:

var myString = "abc";
var n = 3;

new Array(n + 1).join(myString);  // Returns "abcabcabc"


Got any JavaScript Question?