Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I repeat strings in JavaScript? [duplicate]

Tags:

In JavaScript, how would I create a string of repeating strings x number of times:

var s = new String(" ",3);

//s would now be "   "
like image 474
BrokeMyLegBiking Avatar asked Dec 28 '10 22:12

BrokeMyLegBiking


1 Answers

There is no such function, but hey, you can create it:

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

Usage:

var s = " ".repeat(3);

Of course you could write this as part of a standalone group of functions:

var StringUtilities = {
    repeat: function(str, times) { 
       return (new Array(times + 1)).join(str);
    }
    //other related string functions...
};

Usage:

var s = StringUtilities.repeat(" ", 3);
like image 113
Jacob Relkin Avatar answered Oct 12 '22 10:10

Jacob Relkin