Repeat Character N Times

后端 未结 23 2783
栀梦
栀梦 2020-11-22 11:51

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 ac

23条回答
  •  -上瘾入骨i
    2020-11-22 12:27

    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:

提交回复
热议问题