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 "   "
0

5 Answers 5

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);
Sign up to request clarification or add additional context in comments.

6 Comments

I prefer that solution to mine. I didn't know we could append functionality to String class and possibly to any class.
Ahhh, go away with prototype extension...
@Sybiam -- you can, but don't. Well, if it's something universally useful, OK, but something like this, put it in a library.
@Malvolio I updated my answer to accomodate your point of view as well...
@Ivo I personally love prototype extension; why not make use of a language construct that is available to you?
|
5

You can also use Array.join:

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

> repeat(' ', 3)
"   "

Comments

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.

Comments

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.

2 Comments

Perl has the X operator to repeat things like this - there are other languages as well
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.
0

Haven't you tried with a loop

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

?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.