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

← All JS string methods · JS array methods