String.prototype.repeat()
repeat(count) The repeat() method constructs and returns a new string by concatenating the original string with itself a specified number of times. The method accepts a single parameter count that specifies how many copies to repeat. This is useful for generating repeated patterns, padding strings, or creating delimiters programmatically.
The method throws a RangeError if the count is negative or results in a string that exceeds the maximum string length. It also handles edge cases like zero (returns empty string) and fractional values (truncates to integer).
Syntax
string.repeat(count)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
count | number | — | An integer between 0 and Infinity indicating how many times to repeat the string. Non-integer values are converted to integers. |
Parameter Details
- If
countis0, an empty string is returned. - If
countis negative, aRangeErroris thrown. - If
countis a non-integer (like3.5), it gets truncated to the integer part (3). - If
countisInfinity, aRangeErroris thrown because the resulting string would be too long. - The method works on any object with a
toString()method due to its generic nature.
Examples
Basic Repetition
const word = "ha";
console.log(word.repeat(3)); // "hahaha"
console.log(word.repeat(0)); // ""
console.log(word.repeat(1)); // "ha"
Calling repeat(3) on “ha” produces “hahaha” — three copies concatenated together. Passing 0 gives you an empty string, which is handy when you need a default value such as an empty placeholder for conditional logic. Beyond simple string duplication, repeat() serves well for generating visual separators and formatting output. The next example shows how to create dashed lines, indentation, and decorative output with a single method call, avoiding the boilerplate of a loop.
Creating visual elements
const delimiter = "-".repeat(10);
console.log(delimiter); // "----------"
const indent = " ".repeat(4);
console.log(indent + "Indented text");
// " Indented text"
const stars = "*".repeat(5);
console.log(stars); // "*****"
A common use case is generating visual separators or formatting output. This approach is cleaner than using loops for simple tasks. The count argument does not need to be hardcoded — it can come from any expression that resolves to a number. This flexibility makes repeat() especially convenient inside template literals or when the repetition count depends on runtime state, as demonstrated in the next set of examples.
Working with dynamic values
const mood = "Happy! ";
console.log(`I feel ${mood.repeat(3)}`);
// "I feel Happy! Happy! Happy! "
const base = "abc";
const count = 2;
console.log(base.repeat(count)); // "abcabc"
// Fractional values get truncated
console.log("abc".repeat(3.7)); // "abcabcabc"
The method works well with variables and template literals. Non-integer counts are truncated toward zero, so 3.7 becomes 3. This truncation behavior is convenient for quick scripting, but you should validate the count when it comes from user input or an external API. The next section covers the boundary conditions — what happens with negative numbers, Infinity, and objects that define custom toString() methods.
Handling edge cases
// Using with objects that have toString()
const obj = {
toString() { return "obj"; }
};
console.log(Stringrepeat.call(obj, 2)); // "objsbj"
console.log("test".repeat(Infinity)); // RangeError: Invalid string length
console.log("test".repeat(-1)); // RangeError: Invalid count
The method is generic and can be used with any object that implements toString(). Always handle the negative count and Infinity cases with try-catch if the count comes from user input. Once you understand these boundary behaviors, repeat() becomes a versatile utility for many everyday string-generation tasks. The following recipes cover practical patterns you are likely to encounter in production code, from loading indicators to fixed-width column formatting.
Common Patterns
Creating a text-based loading indicator:
function loadingDots(n) {
return ".".repeat(n);
}
console.log(loadingDots(3)); // "..."
console.log(loadingDots(0)); // ""
The loading dots example wraps repeat() in a small helper that produces visual feedback — useful for console spinners or progress indicators. For scenarios where you need text aligned in fixed-width columns, like tabular output in a terminal or a log file, you can combine repeat() with spaces to pad strings to a consistent width. The padRight pattern below handles this by computing how many spaces to append.
Generating aligned columns:
function padRight(str, length) {
return str + " ".repeat(Math.max(0, length - str.length));
}
console.log(padRight("Name", 10) + "John"); // "Name John"
console.log(padRight("Age", 10) + "25"); // "Age 25"
The padRight function uses Math.max as a guard so a string longer than the target width produces zero extra spaces instead of a negative count that would throw. When you need to go beyond padding and generate repeating cell structures — say, for an ASCII table or a grid — you can embed repeat() directly inside a template literal. The next pattern constructs a full table row in a single expression.
Building repeated patterns:
const row = (cell) => `| ${cell} |`.repeat(3);
console.log(row("x")); // "| x | | x | | x |"
The row pattern shows how repeat() works on any string expression, not just simple character literals — the entire template string | ${cell} | gets duplicated. A different use for repeat() is generating fixed-size buffers for testing, where you need a known-length string to exercise allocation, encoding, or I/O code paths. The final pattern creates a 1 KB string with a single call.
Creating test data:
const buffer = "x".repeat(1024); // Create 1KB string
Next Steps
Now that you understand repeat(), explore other string methods for building and manipulating strings. If you need to combine multiple strings into one, concat() is the traditional approach, though template literals often work better for simple cases.
For aligning text within a specific width, padStart() and padEnd() are purpose-built for that task. If you need to extract portions of a string rather than repeat them, slice() works identically to its array counterpart.
See Also
- String.prototype.concat() - Concatenate strings together
- String.prototype.slice() - Extract portions of strings