JavaScript String repeat() Method

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Instance method

What You’ll Learn

String.prototype.repeat() builds a new string by concatenating the original text a given number of times (same API as MDN String.prototype.repeat()). Learn valid counts, RangeError cases, float truncation, separators and fillers, five examples, and try-it labs.

01

Kind

Instance method

02

Returns

New string

03

count

0 … finite

04

Invalid

RangeError

05

Mutates?

No

06

Baseline

Widely available

Introduction

Need the same text several times in a row — a divider line, a laugh ("ha" repeated, or a template phrase? repeat() concatenates copies of the string and returns one new result.

Pass how many copies you want as count. Zero copies give an empty string. Negative values or Infinity throw RangeError. Decimals are truncated to integers.

💡
Beginner tip

Think of str.repeat(n) as str + str + … (n times) — without writing a loop.

This page is part of JavaScript String Methods. Related topics include padStart() and padEnd().

Understanding the repeat() Method

str.repeat(count) returns a new string that contains str concatenated with itself count times.

  • count should be a non-negative finite number.
  • repeat(0) returns "".
  • Floats are truncated (e.g. 3.93).
  • Negative or infinite count throws RangeError.
  • The original string is never modified.

📝 Syntax

General form of String.prototype.repeat:

JavaScript
str.repeat(count)

Parameters

  • count — number of copies. Must be between 0 and a finite value that does not overflow maximum string length. Converted to an integer (truncated toward zero).

Return value

A string with count copies concatenated:

SituationResult
count === 0Empty string ""
count === 1Same as original text
count > 1Text joined that many times
Decimal countTruncated to integer
Negative or InfinityThrows RangeError

Common patterns

JavaScript
"abc".repeat(0);     // ""
"abc".repeat(1);     // "abc"
"abc".repeat(2);     // "abcabc"
"abc".repeat(3.5);   // "abcabcabc"

"ha".repeat(3);      // "hahaha"
"-".repeat(10);      // "----------"

`I feel ${"Happy! ".repeat(3)}`;
// "I feel Happy! Happy! Happy! "

⚡ Quick Reference

GoalCode
Repeat text n timesstr.repeat(n)
Empty resultstr.repeat(0)
Divider line"-".repeat(40)
Join copies with a gapArray(n).fill(str).join(" ")
Pad to a length insteadstr.padStart(n, "0") / padEnd

🔍 At a Glance

Four facts to remember about String.repeat().

Returns
string

n copies joined

count 0
""

Empty string

Bad count
RangeError

Negative / Infinity

Mutates
no

Strings stay immutable

📋 repeat() vs padStart() / padEnd() vs a loop

repeat()padStart / padEndManual loop
GoalCopy whole string n timesReach a target length with fillerAnything custom
Best forPatterns, dividers, templatesZero-padding, fixed columnsConditional builds
Invalid inputRangeErrorUsually just no-opsYour own checks
ReadabilityClearest for copiesClearest for widthVerbose

Examples Gallery

Examples follow MDN String.repeat() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

Repeat a phrase and explore count values.

Example 1 — Basic repeat()

MDN demo: insert a repeated mood phrase into a sentence.

JavaScript
const mood = "Happy! ";

`I feel ${mood.repeat(3)}`;
// "I feel Happy! Happy! Happy! "
Try It Yourself

How It Works

mood.repeat(3) concatenates "Happy! " three times. The template literal places that block after "I feel ".

Example 2 — Count Values (Including Floats)

MDN walkthrough of common repeat results.

JavaScript
"abc".repeat(0);    // ""
"abc".repeat(1);    // "abc"
"abc".repeat(2);    // "abcabc"
"abc".repeat(3.5);  // "abcabcabc"  (truncated to 3)
Try It Yourself

How It Works

0 copies produce an empty string. Decimal counts are truncated toward zero before repeating — 3.5 becomes 3.

📈 Practical Patterns

Dividers, separators, and error handling.

Example 3 — Divider Lines and Indentation

Build visual separators and simple indentation without loops.

JavaScript
"-".repeat(20);
// "--------------------"

const indent = "  ".repeat(2);
indent + "nested item";
// "    nested item"

"*".repeat(5) + " STAR " + "*".repeat(5);
// "***** STAR *****"
Try It Yourself

How It Works

Single-character strings make neat lines. Repeating two spaces builds indentation levels for text trees or logs.

Example 4 — Copies With a Separator

repeat itself does not insert separators — combine it with Array + join when you need gaps.

JavaScript
"ha".repeat(3);
// "hahaha"  (no spaces)

Array(3).fill("ha").join(" ");
// "ha ha ha"

Array(4).fill("●").join("-");
// "●-●-●-●"
Try It Yourself

How It Works

Use repeat for back-to-back copies. Use Array(n).fill(str).join(sep) when each copy needs a separator.

Example 5 — RangeError Cases

MDN notes: negative counts and Infinity throw.

JavaScript
try {
  "abc".repeat(-1);
} catch (e) {
  e.name;  // "RangeError"
}

try {
  "abc".repeat(1 / 0);  // Infinity
} catch (e) {
  e.name;  // "RangeError"
}

// Generic method (works on other objects with toString):
({ toString: () => "abc", repeat: String.prototype.repeat }).repeat(2);
// "abcabc"
Try It Yourself

How It Works

Validate count before calling when it comes from user input. repeat is generic — it uses this converted to a string.

🚀 Common Use Cases

  • Divider / ruler lines"-".repeat(40) in console or reports.
  • Indentation" ".repeat(level * 2) for tree-style logs.
  • Decorative banners — stars or equals around a title.
  • Template phrases — repeat a unit inside larger strings.
  • Not for fixed width — prefer padStart / padEnd when the goal is a target length.
  • Not for huge counts — very large count can throw or exhaust memory.

🧠 How repeat() Builds the Result

1

Read count

Convert count to an integer (truncate toward zero).

Input
2

Validate range

Reject negatives and values that overflow string limits with RangeError.

Guard
3

Concatenate copies

Join the string with itself count times (or return "" for 0).

Build
4

Return a new string

The original str is unchanged.

📝 Notes

  • repeat(0) returns "" — it does not throw.
  • Negative count or Infinity throws RangeError.
  • Decimals are truncated toward zero before repeating.
  • repeat does not insert separators between copies.
  • Very large counts can throw if the result would be too long.
  • The method is generic — it can run on other objects that coerce to strings.

Browser & Runtime Support

String.prototype.repeat() is Baseline Widely available — supported across modern browsers since September 2015.

Baseline · Widely available

String.repeat()

Safe for production. Prefer repeat() for copying text; use padStart/padEnd when you need a target length.

Universal Widely available
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
repeat() Excellent

Bottom line: Use String.repeat() to concatenate copies of a string. Guard against negative or infinite counts, and remember floats are truncated.

Conclusion

String.prototype.repeat() is the clear way to build a string from repeated copies — dividers, indentation, and template phrases without a loop. Validate count, and reach for padStart / padEnd when your goal is a fixed width instead.

Continue with padStart(), padEnd(), or the String methods hub.

💡 Best Practices

✅ Do

  • Use repeat() when you need n copies of the same text
  • Validate user-provided count before calling
  • Use Array(n).fill(str).join(sep) when you need separators
  • Prefer padStart / padEnd for fixed-width padding
  • Keep counts reasonable for memory and performance

❌ Don’t

  • Pass negative numbers or Infinity without a try/catch
  • Expect spaces between copies from repeat alone
  • Use repeat when you really need a target length
  • Assume decimals round up — they truncate
  • Mutate strings — always capture the returned value

Key Takeaways

Knowledge Unlocked

Five things to remember about String.repeat()

Concatenate copies of a string n times.

5
Core concepts
🔎 02

count 0

empty ""

Rule
03

Bad count

RangeError

Guard
04

Floats

truncated

Coerce
📄 05

Mutates

no

Immutable

❓ Frequently Asked Questions

String.prototype.repeat(count) returns a new string made of the original text concatenated count times. For example "ha".repeat(3) returns "hahaha".
repeat(0) returns an empty string "". That is valid and does not throw.
A negative count, or a count that is Infinity (or otherwise too large for a string), throws RangeError.
count is converted to an integer (truncated toward zero), so "abc".repeat(3.5) behaves like "abc".repeat(3).
No. Strings are immutable. repeat() returns a new string.
repeat copies the whole string n times. padStart/padEnd grow a string to a target length by adding a filler on one side — they do not mean “copy the string n times.”
Did you know?

Before repeat() (ES2015), a common trick was new Array(n + 1).join(str) — clever, but easy to off-by-one. str.repeat(n) makes the intent obvious.

More String Methods

Return to the hub for slice, trim, replace, and more.

String methods hub →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful