Skip to content

3 Ways to Repeat a String in JavaScript

    The repeat() method of String

    In ES6, String has added a repeat() method, which returns a new string by specifying the count.

    It will output bitbugbitbugbitbug.

    Repeating strings can be easily created using the repeat method, but IE11 does not support this method.

    Using the API of Array

    Array has a lot of APIs, so there will be many implementations. But the steps are similar, first construct an empty array of specified length, then fill in the string, and finally convert it to a string.

    Using fill() method of Array

    If we want to repeat a string , we can do it with fill() method to fill string into array instance, then covert it to a string.

    function repeatString(string, count) { return Array(count).fill(string).join('');}

    We can test it by repeating bitbug 3 times:

    Using join() method of Array

    When converting an Array to a string, you can use the join() method. The join() method will concatenate all elements in the array through a separator. We can custom the separator by using the string which needed to be repeat.

    function repeatString(string, count) { return Array(count + 1).join(string);


    Note that the length of the constructed array needs to be greater than the number of repeating string.

    Using reduce() method of Array

    We can use Array’s iterator method to construct a new string by iterating over all elements of the array.

    function repeatString(string, count) { return Array(count).toString().split(',').reduce(pre => pre + string, '');}


    It should be noted that if the array is empty, the reduce() method will not be executed, so it needs to be filled with empty string.

    Repeat a string with a while loop

    A while statement executes its statement as long as a specified condition evaluates is true.

    function repeatString(string, count) { let result = ''; while (count) { result+= string; count--; } return result;}


    When the amount of data is relatively large, the while loop can be optimized using the dichotomy method.

    // Code from repeatString(string, count) { let result = ''; while (count) { if (count % 2 === 1) { result += string; } if (count > 1) { string += string; } count >>= 1; } return result;}



    Although three ways of repeating strings are introduced, the native repeat() method is recommended. If you need to use it in the production environment, you need to pay attention to whether it needs to be compatible with IE11 and choose the corresponding solution.

    SOURCE :