JavaScript String repeat()

The repeat() method creates a new string by repeating the given string a specified number of times and returns it.

Example

const holiday = "Happy holiday!";

// repeating the given string 3 times const result = holiday.repeat(3);
console.log(result); // Output: // Happy holiday!Happy holiday!Happy holiday!

repeat() Syntax

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.

repeat() Return Value

  • 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 1: Using repeat() Method

// string declaration
const holiday = "Happy holiday!";

// repeating the given string 2 times const result = holiday.repeat(2);
console.log(result);
// using 0 as a count value // returns an empty string let result2 = holiday.repeat(0);
console.log(result2);

Output

Happy holiday!Happy holiday!

In the above program, holiday.repeat(2) repeats the string stored in holiday 2 times.

When we pass 0 as a parameter, the method repeats holiday 0 times. That's why holiday.repeat(0) doesn't print anything (prints empty string).


Example 2: Using Non-integer as a Count Value in repeat()

let sentence = "Happy Birthday to you!";

// using non-integer count value let result1 = sentence.repeat(3.2);
console.log(result1);
// using non-integer count value let result2 = sentence.repeat(3.7);
console.log(result2);

Output

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

Here, the non-integer index values 3.2 and 3.7 are converted to the nearest integer index 3. So, both sentence.repeat(3.2) and sentence.repeat(3.7) repeats the string 3 times.


Example 3: Using Negative Number as a Count Value

The count value in the repeat() method must be a non-negative number. Otherwise, it throws an error. For example:

let sentence = "Happy Birthday to you!";

// using negative number as count value let result3 = sentence.repeat(-1);
console.log(result3);

Output

RangeError: Invalid count value

Also Read:

Did you find this article helpful?