20

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

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

//s would now be "   "
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
BrokeMyLegBiking
  • 5,898
  • 14
  • 51
  • 66

5 Answers5

55

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);
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
5

You can also use Array.join:

function repeat(str, times) {
    return new Array(times + 1).join(str);
}

> repeat(' ', 3)
"   "
Ivo Wetzel
  • 46,459
  • 16
  • 98
  • 112
5

Here's a neat way that involves no loops. In addition to being concise, I'm pretty sure using join is much more efficient for very large strings.

function repeat(str, num) { 
    return (new Array(num+1)).join(str); 
}

You could also put this code on the String prototype, but I'm of the mindset that it's a bad idea to mess with the prototype of built in types.

peepsalot
  • 422
  • 4
  • 7
2

I think your best and only way to achieve this is to loop over your string.. As far as I know, there is no such feature in any languages.

function multiString(text, count){
    var ret = "";
    for(var i = 0; i < count; i++){
        ret += text;
    }
    return ret;
}

var myString = multiString("&nbsp;", 3);

But I guess you could figure it out.

Loïc Faure-Lacroix
  • 13,220
  • 6
  • 67
  • 99
  • Perl has the X operator to repeat things like this - there are other languages as well – Good Person Dec 29 '10 at 02:42
  • I know in python and from a solution bellow we can do it with arrays and join. But I don't consider these solutions as features. I don't know about the X operator but nowadays I'm not surprised about Perl. After I saw the Periodic table of operators for perl. Nothing will surprise me anymore. – Loïc Faure-Lacroix Dec 30 '10 at 14:29
0

Haven't you tried with a loop

for (var i = 0; i < 3; i++) {
     s += "&nbsp;"; }

?

Carlos Valenzuela
  • 816
  • 1
  • 7
  • 19