repeat method

The repeat method creates a new string containing the specified number of copies of the original string concatenated together.

Syntax

javascriptstring.repeat(number);

Example

Let's specify the number 1 in the method parameter:

javascriptlet res = 'abcde'.repeat(1);
console.log(res);

As a result of executing the code, our string will remain the same:

javascript'abcde'

Example

Now we will copy the string 2 times:

javascriptlet res = 'abcde'.repeat(2);
console.log(res);

The code execution result:

javascript'abcdeabcde'

Example

Let's try to copy the string -1 times:

javascriptlet res = 'abcde'.repeat(-1);
console.log(res);

After execution we get an error:

javascript'RangeError: Invalid count value: -1'

Example

If we specify the number 0 in the parameter:

javascriptlet res = 'abcde'.repeat(0);
console.log(res);

As a result of executing the code, we will get an empty string:

javascript''

See also

  • the padEnd method
    that pads the current string from its end with a given string
  • the padStart method
    that pads the current string from its start with a given string