Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท String

String.prototype.repeat()

Reference for JavaScript String.prototype.repeat(): build a new string by repeating text a number of times, with examples for dividers, indents and simple bar charts.

The repeat() method returns a new string made of the original string copied a given number of times, joined with nothing in between. It is the clean way to build dividers, indentation and simple text graphics without a loop.

The count must be a non-negative, finite number. Zero gives an empty string, and invalid counts raise a RangeError instead of failing quietly.

JavaScript
"ab".repeat(3); // "ababab"

Try it

JS Dividers, indents and bars

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Counts and errors

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
string.repeat(count)
Name Description
count How many copies to join. It is converted to an integer: fractions are truncated, and NaN or a missing value becomes 0. It must end up between 0 and +Infinity exclusive, and the result must be a valid string length.

Return value: a new string with count copies of the original, or an empty string if count is 0 or the original is empty.

Exceptions: a RangeError if count is negative, is Infinity, or would produce a string longer than the engine allows.

Usage notes

  • Fractions are cut, not rounded: "ha".repeat(2.9) is "haha". Anything between 0 and 1 becomes 0 copies, and -0.5 also truncates to 0 without an error.
  • No separator. To put something between copies, build an array and call join(): Array(3).fill("ab").join("-") gives ab-ab-ab.
  • Guard user-controlled counts. A huge number can allocate a lot of memory or throw, so clamp it: "-".repeat(Math.min(count, 80)).
  • Padding: padStart() and padEnd() repeat a pad string for you; use repeat() when you need an exact number of copies.
  • Converts the count, not the receiver. The string is the thing being repeated; only the argument goes through number conversion.
  • Immutable. The original string is untouched.
  • Arrays do not have it. To repeat array contents, use Array.from({ length: n }, () => value) or new Array(n).fill(value).
  • Bar charts in text are a fine use. For anything the user will actually look at in a page, use CSS or SVG.

Browser support

repeat() is part of ES2015 and works in all current browsers.