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>

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

      let myString = "";
      let res = myString.repeat(3);
      document.getElementById("xyz").innerHTML = res;

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

let myString = "";

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 "" 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 "" will be displayed inside the "p" tag with ID "xyz."

JavaScript repeat() Syntax

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


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 post? Share it!