transformation
String.prototype.repeat
Returns a new string containing count copies of the original string concatenated together. Added in ES2015; count must be a non-negative finite integer.
str.repeat(count) Parameters
| Parameter | Purpose |
|---|---|
| count | Coerced to an integer (fractional values are truncated). RangeError is thrown on negatives, Infinity, or when the result would exceed the implementation's maximum string length. |
| returns | New string of count copies; RangeError if negative or Infinity |
Examples
console.log('ab'.repeat(3)); Prints 'ababab'
console.log('-'.repeat(5)); Prints '-----'
console.log('x'.repeat(0)); Prints '' (empty string)
try { 'x'.repeat(-1); } catch (e) { console.log(e.name); } Prints 'RangeError'
Gotcha
Fractional counts are truncated toward zero. Negative counts and Infinity throw RangeError; results exceeding the maximum string length also throw.
Related methods
String.prototype.padStart
Returns a new string padded on the left with padString (default ' ') until it reaches targetLength. Added in ES2017; the original is returned unchanged if it is already long enough.
String.prototype.padEnd
Returns a new string padded on the right with padString (default ' ') until it reaches targetLength. Added in ES2017.
String.prototype.split
Divides the string into an array of substrings using separator (string or RegExp). With no separator the whole string is returned as a one-element array; with '' each UTF-16 code unit becomes an element.
String.prototype.replace
Returns a new string with the first match of pattern replaced. Pattern can be a string (only the first occurrence) or a RegExp (all occurrences when the g flag is set).
String.prototype.replaceAll
Returns a new string with every occurrence of pattern replaced. Added in ES2021; if pattern is a RegExp it must have the g flag or replaceAll throws TypeError.