Nate Woods

Nate Woods

JavaScript Repeat a string

2013-02-21

After writing writing my fair share of for-loops, I decided there must be a better way to repeat a string.  Personally, I found this solution to be very elegant and hopefully will help you as much as it helped me.

String.prototype.repeat = function(n) {
     return new Array(1 + n).join(this);
}

Sample usage: alert("ha".repeat(5)); // hahahahaha

[Source]

×