开发者

How can I repeat strings in JavaScript? [duplicate]

开发者 https://www.devze.com 2023-02-01 06:41 出处:网络
This question already has answers here: 开发者_开发知识库 Repeat String - Javascript [duplicate]
This question already has answers here: 开发者_开发知识库 Repeat String - Javascript [duplicate] (30 answers) Closed 9 years ago.

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

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

//s would now be "   "


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);


You can also use Array.join:

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

> repeat(' ', 3)
"   "


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.


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.


Haven't you tried with a loop

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

?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号