Repeat Character N Times

2019-01-01 06:25发布

In Perl I can repeat a character multiple times using the syntax:

$a = "a" x 10; // results in "aaaaaaaaaa"

Is there a simple way to accomplish this in Javascript? I can obviously use a function, but I was wondering if there was any built in approach, or some other clever technique.

21条回答
姐姐魅力值爆表
2楼-- · 2019-01-01 06:34

I'm going to expand on @bonbon's answer. His method is an easy way to "append N chars to an existing string", just in case anyone needs to do that. For example since "a google" is a 1 followed by 100 zeros.

for(var google = '1'; google.length < 1 + 100; google += '0'){}
document.getElementById('el').innerText = google;
<div>This is "a google":</div>
<div id="el"></div>

NOTE: You do have to add the length of the original string to the conditional.

查看更多
高级女魔头
3楼-- · 2019-01-01 06:35

Here is what I use:

function repeat(str, num) {
        var holder = [];
        for(var i=0; i<num; i++) {
            holder.push(str);
        }
        return holder.join('');
    }
查看更多
泪湿衣
4楼-- · 2019-01-01 06:38

Convenient if you repeat yourself a lot:

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

alert(  'Are we there yet?\nNo.\n'.repeat(10)  )

查看更多
不流泪的眼
5楼-- · 2019-01-01 06:38

For all browsers

The following function will perform a lot faster than the option suggested in the accepted answer:

var repeat = function(str, count) {
    var array = [];
    for(var i = 0; i < count;)
        array[i++] = str;
    return array.join('');
}

You'd use it like this :

var repeatedString = repeat("a", 10);

To compare the performance of this function with that of the option proposed in the accepted answer, see this Fiddle and this Fiddle for benchmarks.

For moderns browsers only

In modern browsers, you can now do this using String.prototype.repeat method:

var repeatedString = "a".repeat(10);

Read more about this method on MDN.

This option is even faster. Unfortunately, it doesn't work in any version of Internet explorer. The numbers in the table specify the first browser version that fully supports the method:

enter image description here

查看更多
后来的你喜欢了谁
6楼-- · 2019-01-01 06:38

Lodash offers a similar functionality as the Javascript repeat() function which is not available in all browers. It is called _.repeat and available since version 3.0.0:

_.repeat('a', 10);
查看更多
查无此人
7楼-- · 2019-01-01 06:39

If you're not opposed to including a library in your project, lodash has a repeat function.

_.repeat('*', 3);
// → '***

https://lodash.com/docs#repeat

查看更多
登录 后发表回答