Description
The JavaScript String method repeat()
creates and returns a new string by repeating the given string a specific number of times.
Syntax
The method repeat()
has the below syntax, where str
is a string.
str.repeat(count)
Parameters
The method repeat()
allows the below parameters.
count
- It is an integer that defines the number of times to repeat a string.
- It takes a value between 0 and +Infinity.
Result
The method repeat()
returns a new string by repeating the given string by count
times.
- Returns
RangeError
if thecount
is negative, Infinity, or it results in a string that overflows the maximum string size.
Example 1: Using the Method
Here is the basic use of this method.
var str = "Hello";
// Repeating a string 3 times
document.write(str.repeat(3)); // Prints: HelloHelloHello
// Repeating a string 0 times
document.write(str.repeat(0)); // Returns an empty string
// Repeating a string -3 times
document.write(str.repeat(-3)); // RangeError: Invalid count value: -3
// Repeating a string Infinity times
document.write(str.repeat(Infinity)); // RangeError: Invalid count value: Infinity
Output:
HelloHelloHello
Example 2: Using Non-Integer Number for Count
For a non-integer number for the count parameter, the method converts the count to the nearest smaller integer ignoring the decimal digits.
var str = "Hello";
// Repeating a string 3 times
document.write(str.repeat(3)); // Prints: HelloHelloHello
// Repeating a string 3.2 times
document.write(str.repeat(3.2)); // Prints: HelloHelloHello
// Repeating a string 3.9 times
document.write(str.repeat(3.9)); // Prints: HelloHelloHello
Output:
HelloHelloHello
HelloHelloHello
HelloHelloHello
Example 3: Method Issues RangeError
For negative and Infinity numbers for the count parameter, the method issues a RangeError.
var str = "Hello";
// Using negative number for count
document.write(str.repeat(-3)); // RangeError: Invalid count value
// Using Inifnity for count
document.write(str.repeat(Infinity)); // RangeError: Invalid count value
Output:
RangeError: Invalid count value: -3
RangeError: Invalid count value: Infinity
Overall
The JavaScript String method repeat()
returns a new string containing the specified number of copies of a string.