JavaScript - repeat() method

revision:


Category : string

The repeat() method returns a string with a number of copies of a string. It returns a new string, but does not change the original string.

Syntax :

        string.repeat(count)
    

Parameters:

: required. The number of copies.

Examples:

        <p>repeat() returns a new string with a number of copies of a string:</p>
        <p id="demo"></p>
        <p>repeat() is not supported in Internet Explorer.</p>
        <script>
            let text = "Hello world!";
            let result = text.repeat(2);
            document.getElementById("demo").innerHTML = result;
        </script>

    

Practical examples

example: create copies of a text.

repeat() returns a new string with a number of copies of a string:

code:
                    <div>
                        <p>repeat() returns a new string with a number of copies of a string:</p>
                        <p id="repeat-1"></p>
                        <p id="repeat-2"></p>
                        <p id="repeat-3"></p>
                        <p id="repeat-4"></p>
                        <p id="repeat-5"></p>
                        <p id="repeat-6"></p>
                    </div>
                    <script>
                        let text = "Hello world!";
                        document.getElementById("repeat-1").innerHTML = "string : " + text;
                        let result = text.repeat(2);
                        document.getElementById("repeat-2").innerHTML = "result : " + result;
                        let result1 = text.repeat(4);
                        document.getElementById("repeat-3").innerHTML = "result : " + result1;
                        let text1 = " Hello world! ";
                        document.getElementById("repeat-4").innerHTML = "string : " + text1;
                        let result2 = text1.repeat(2);
                        document.getElementById("repeat-5").innerHTML = "result : " + result2;
                        let result3 = text1.repeat(4);
                        document.getElementById("repeat-6").innerHTML = "result : " + result3;
                    </script>