JavaScript String repeat()

The JavaScript String repeat() method returns a new string by copying and concatenating the given string a specified number of times.

The syntax of the repeat() method is:

str.repeat(count)

Here, str is a string.


repeat() Parameters

The repeat() method takes in :

  • count - An integer between 0 and +Infinity, indicating the number of times to repeat the string.

Return value from repeat()

  • Returns a new string containing the specified number of copies of the given string.

Note: repeat() raises RangeError if repeat count is negative, infinity, or overflows maximum string size.


Example: Using repeat() method

let sentence = "Happy Birthday to you! ";

let repeat1 = sentence.repeat(2);
console.log(repeat1); // 'Happy Birthday to you! Happy Birthday to you!'

// count is converted to integer
let repeat2 = sentence.repeat(3.5);
// 'Happy Birthday to you! Happy Birthday to you! Happy Birthday to you!'
console.log(repeat2);

let repeat3 = sentence.repeat(0);
console.log(repeat3); // ''

// RangeError if count is negative or infinite
let repeat4 = sentence.repeat(-1);
console.log(repeat4); // RangeError: Invalid count value

Output

Happy Birthday to you! Happy Birthday to you! 
Happy Birthday to you! Happy Birthday to you! Happy Birthday to you! 

error: Uncaught RangeError: Invalid count value

Recommended Reading: JavaScript String concat()