JavaScriptStrings

String.prototype.repeat()

Returns a new string made up of the given number of copies of the original.

Returns
A new string containing count copies of the original.
Changes the original
No
On this page

Example

#
JavaScript
console.log('=-'.repeat(10))
console.log('β˜…'.repeat(4))
console.log('ha'.repeat(3))
Console
=-=-=-=-=-=-=-=-=-=-
β˜…β˜…β˜…β˜…
hahaha

Definition and usage

#

The repeat() method joins a string with itself as many times as you specify. "ab".repeat(3) gives "ababab", and repeat(0) returns an empty string.

It comes in handy for generating separators, indentation, simple progress bars, stars in ratings, or masking a piece of text. Instead of a loop that concatenates characters, a single call does the job.

The repeat count must be non-negative and finite. A negative value or Infinity throws a RangeError, and fractions are truncated, so 2.7 behaves like 2. The original stays unchanged.

Syntax

#
Syntax
string.repeat(count)

Parameters

#
  • count

    number

    The number of repetitions, 0 or higher. A fraction is truncated, and a negative or infinite value throws a RangeError.

More examples

#
A progress bar
JavaScript
function progressBar(done, total) {
  const filled = Math.round((done / total) * 10)
  return 'β–ˆ'.repeat(filled) + 'β–‘'.repeat(10 - filled) + ` ${done}/${total}`
}

console.log(progressBar(3, 10))
console.log(progressBar(7, 7))
Console
β–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘β–‘ 3/10
β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ 7/7
Indentation in a course tree
JavaScript
const tree = [
  ['Course', 0],
  ['Module 1', 1],
  ['Lesson 1', 2],
  ['Module 2', 1]
]

for (const [label, depth] of tree) {
  console.log(' '.repeat(depth * 2) + label)
}
Console
Course
Module 1
Lesson 1
Module 2
Fractions, zero, and negative values
JavaScript
console.log('ab'.repeat(2.7))
console.log('ab'.repeat(0).length)

try {
  'ab'.repeat(-1)
} catch (error) {
  console.log(error.name)
}
Console
abab
0
RangeError

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • A repeat count calculated from data, such as 10 - filled, can end up negative. Guard it with Math.max(0, n) to avoid a RangeError.
  • A very large repeat count creates a huge string and can freeze the page. The engine also has an upper limit on string length.

Related entries

#

Spotted a mistake or missing an example? Write to us.