Formatting text
Generate a visual divider or indentation by repeating a character or short string.
JavaScript · Function
String.prototype.repeat() returns a new string containing the receiver repeated a specified number of times. The count is converted to an integer and invalid or excessive counts throw RangeError.
String.prototype.repeat() returns a new string made by concatenating the receiver a specified number of times. The count is converted to an integer; zero produces an empty string, while invalid or overly large counts throw a RangeError.
repeat(count)| Name | Type | Description |
|---|---|---|
count | number | An integer between 0 and Infinity indicating how many times to repeat the string. |
A new string containing the specified number of copies of the given string.
const separator = "-";
const result = separator.repeat(5);
console.log(result); // "-----"Creates a five-character separator by concatenating five copies of the same string.
Generate a visual divider or indentation by repeating a character or short string.
Create a repeated token sequence when building output or test fixtures.
Produce padding based on a calculated width.
It returns a new string containing the receiver repeated count times. A count of zero returns an empty string.
Follow-up: What happens with a fractional count? It is converted to an integer, so 3.5 behaves like 3.
The count must be non-negative and finite, and the resulting string must fit within the maximum string length. Otherwise, the method throws RangeError.
Follow-up: Does Infinity mean unlimited repetition? No. Infinity is invalid and results in RangeError.
repeat() is generic: it can be borrowed by an object whose this value can be converted to a string. For example, an object with toString() returning "abc" can use String.prototype.repeat.call(object, 2).
Follow-up: What must a borrowed receiver provide? It must be coercible to a string; the method does not require a String instance.
StringString.prototype.toStringString.prototype.concat