JavaScript repeat(): Repeat String n Times

The JavaScript repeat() method is used when we need to repeat a string for n number of times. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

   <script>
      let myString = "codescracker.com";
      
      let res = myString.repeat(3);
      document.getElementById("xyz").innerHTML = res;
   </script>
   
</body>
</html>
Output

The code in the preceding example creates a string variable named myString and assigns the value "codescracker.com" to it.

let myString = "codescracker.com";

The repeat() function is called on the myString variable with an argument of 3. The repeat() function returns a new string consisting of the original string repeated a specified number of times.

let res = myString.repeat(3);

In this case, the new string returned by the repeat() function will contain three copies of the original string "codescracker.com" concatenated together.

The resulting string is assigned to a new variable named res.

Finally, the innerHTML property of an HTML element with ID "xyz" is set to the value of the res variable.

document.getElementById("xyz").innerHTML = res;

As a result, when the code is executed, the string "codescracker.comcodescracker.comcodescracker.com" will be displayed inside the "p" tag with ID "xyz."

JavaScript repeat() Syntax

The syntax of the repeat() method in JavaScript is:

string.repeat(n)

The n argument is required and refers to a number that is used to create a number of copies of the specified string.

Advantages of the repeat() function in JavaScript

Disadvantages of the repeat() function in JavaScript

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this article? Share it!





Like/follow us on social media for updates!




Like/follow us on social media for updates!