References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript string.repeat() method

Method JavaScript All modern browsers Updated
Quick answer

The repeat() method returns a new string made by repeating the original a given number of times. "ab".repeat(3) gives "ababab". A count of 0 returns an empty string; a negative count throws a RangeError. It's handy for separators, indentation and simple text bars.

Overview

repeat() builds a string by stamping out copies of another. "=".repeat(20) gives a twenty-character line of equals signs — perfect for separators in console output, ASCII bars, or repeated indentation. It returns a new string and doesn't change the original.

The count rules are simple but have edges. 0 gives an empty string. A fractional count is rounded down ("x".repeat(2.9) is "xx"). A negative count, or one so large it would overflow, throws a RangeError — so guard the count if it comes from user input or a calculation that could go negative.

It's a small, focused method. For building dynamic content you'll more often use template literals or join(), but for "repeat this exact string N times" nothing is more direct than repeat().

Syntax

str.repeat(count)

"ab".repeat(3)   // "ababab"
"=".repeat(10)   // "=========="
"x".repeat(0)    // ""

Parameters

The string.repeat() method accepts the following parameters.

Parameter Description
count The number of times to repeat the string. Must be a non-negative number; negatives throw a RangeError.

Example

Live example
<pre id="out" style="font:14px ui-monospace,monospace"></pre>
<script>
  function bar(value, max) {
    const filled = Math.round((value / max) * 20);
    return '[' + '#'.repeat(filled) + '-'.repeat(20 - filled) + '] ' + value + '%';
  }

  document.getElementById('out').textContent =
    bar(25, 100) + '\n' + bar(70, 100);
</script>

Best practices

  • Use it for separators, bars and repeated indentation.
  • Guard the count against negative values, which throw a RangeError.
  • Remember a count of 0 returns an empty string, and fractions are rounded down.
  • For joining a list with a separator, join() is the better tool than building with repeat().

Frequently asked questions

What does repeat() do in JavaScript?
It returns a new string consisting of the original repeated the given number of times, e.g. "ab".repeat(2) is "abab".
Why does repeat() throw a RangeError?
Because the count was negative or too large. The count must be a non-negative, finite number.
What does repeat(0) return?
An empty string "".
How do I repeat a string a fractional number of times?
You can't partially repeat — the count is rounded down, so "x".repeat(2.9) gives "xx".