When working with JavaScript, you may encounter situations where you need to repeat a string a specific number of times.
Whether you’re generating repeated patterns or simply duplicating text, the repeat()
method provides a simple and effective way to achieve this.
The repeat()
method is a built-in function in JavaScript that allows you to repeat a string a specified number of times. Here is the basic syntax:
string.repeat(count);
string
is the string that you want to repeat, and count
is the number of times you want the string to be repeated. Here’s an example:
let word = "Hello!";
let repeatedWord = word.repeat(3);
console.log(repeatedWord); // Output: "Hello!Hello!Hello!"
In this case, the string Hello!
is repeated three times, resulting in Hello!Hello!Hello!
.
While the repeat()
method is useful, there are a few exceptions and limitations to keep in mind.
The count
parameter must be a non-negative number. If you pass a negative number, JavaScript will throw a RangeError
.
let word = "Test";
console.log(word.repeat(-1)); // Throws RangeError: Invalid count value
The count
must be a finite number. If you try to repeat a string an infinite number of times or use Infinity
as the count, you will also get a RangeError
.
In JavaScript, Infinity
is a special value that represents an infinite quantity. It’s used to denote numbers that are larger than any finite number.
let word = "Test";
console.log(word.repeat(Infinity)); // Throws RangeError: Invalid count value
If the count is not an integer (such as a decimal like 2.5
), the repeat()
method will round it down to the nearest integer.
let word = "Test";
console.log(word.repeat(2.5)); // Output: "TestTest"
If you pass 0
as the count, the repeat()
method will return an empty string.
let word = "Test";
console.log(word.repeat(0)); // Output: ""
The repeat()
method can simplify tasks that involve string duplication, making your code more concise and readable.
Whether you’re generating repeated text patterns or filling a space with characters, repeat()
can save you from writing loops or more complex code.