How to Repeat Text: Uses, Techniques, and Code Examples
Repeating text is a surprisingly common developer task: generating dummy data for a form, filling a textarea with placeholder content, creating a repeated CSS pattern, or stress-testing a field that has a character limit. Every major language has a one-liner for it — but the details (separators, large outputs, Unicode safety) trip people up more than they should.
This guide covers why and when you'd repeat text, how to do it in four languages, separator strategies, and the pitfalls to avoid.
When Would You Repeat Text?
| Use case | Example |
|---|---|
| Dummy data for forms | Fill a 255-char name field to test truncation |
| SQL seed data | INSERT INTO t VALUES ('a'), ('a'), … for 1 000 rows |
| CSS repeated patterns | background: repeating-linear-gradient(…) via inline style |
| Load / stress testing | Send a 1 MB request body to check server limits |
| Unit tests | Assert that a parser handles 500 identical tokens |
| Lorem ipsum alternative | Repeat a real sentence to match exact byte count |
| CLI output simulation | Repeat a log line to fill a buffer |
The Core Idea
Repeating a string N times with a separator has three variables:
- Input text — the unit you repeat
- Count — how many times
- Separator — what goes between repetitions (
\n,,,, or nothing)
output = text + sep + text + sep + text // 3 times, with separator
output = [text, text, text].join(sep) // same, cleaner
Joining an array is the safest approach in every language — it avoids a trailing separator that a pure concatenation loop would produce.
Code Examples
JavaScript
// Built-in: String.prototype.repeat (no separator)
const raw = "hello".repeat(5);
// "hellohellohellohellohello"
// With separator
function repeatText(text, times, sep = "\n") {
if (times < 1) return "";
return Array.from({ length: times }, () => text).join(sep);
}
console.log(repeatText("ping", 4, " "));
// "ping ping ping ping"
console.log(repeatText("item", 3, ",\n"));
// "item,\nitem,\nitem"
String.prototype.repeat is fastest for no-separator cases. For separators, Array.from + join is idiomatic and avoids a trailing separator.
Python
# Built-in: * operator (no separator)
raw = "hello" * 5
# "hellohellohellohellohello"
# With separator
def repeat_text(text: str, times: int, sep: str = "\n") -> str:
if times < 1:
return ""
return sep.join([text] * times)
print(repeat_text("ping", 4, " "))
# "ping ping ping ping"
print(repeat_text("row", 3, ",\n"))
# "row,\nrow,\nrow"
sep.join([text] * times) is the Pythonic one-liner. The list [text] * times does not copy the string's bytes repeatedly — Python interns short strings, so memory usage stays low until you actually build the joined result.
Go
package main
import (
"fmt"
"strings"
)
// No separator
func repeatRaw(s string, n int) string {
return strings.Repeat(s, n)
}
// With separator
func repeatText(text string, n int, sep string) string {
if n < 1 {
return ""
}
parts := make([]string, n)
for i := range parts {
parts[i] = text
}
return strings.Join(parts, sep)
}
func main() {
fmt.Println(repeatRaw("ab", 4)) // "abababab"
fmt.Println(repeatText("ping", 3, " | ")) // "ping | ping | ping"
}
strings.Repeat is the standard library function for the no-separator case. For separators, strings.Builder is the most memory-efficient approach for very large outputs:
func repeatTextBuilder(text string, n int, sep string) string {
if n < 1 {
return ""
}
var b strings.Builder
b.Grow(len(text)*n + len(sep)*(n-1)) // pre-allocate
for i := 0; i < n; i++ {
if i > 0 {
b.WriteString(sep)
}
b.WriteString(text)
}
return b.String()
}
PHP
// No separator
$raw = str_repeat("hello", 5);
// "hellohellohellohellohello"
// With separator
function repeatText(string $text, int $times, string $sep = "\n"): string {
if ($times < 1) return "";
return implode($sep, array_fill(0, $times, $text));
}
echo repeatText("ping", 4, " "); // "ping ping ping ping"
echo repeatText("row", 3, ",\n"); // "row,\nrow,\nrow"
str_repeat handles the no-separator case. array_fill + implode is the idiomatic approach for separators.
Separator Reference
| Separator | Use case | Code literal |
|---|---|---|
| None | Concatenated words, padding | "" |
| Space | Sentence-like dummy content | " " |
| Newline | Line-by-line data, log simulation | "\n" |
, |
CSV values, array literals | ", " |
| |
Markdown tables | " | " |
\n---\n |
Markdown section dividers | "\n---\n" |
; |
SQL value lists | ";" |
Performance Considerations
Repeating a 100-character string 10 000 times produces a 1 MB string — that's fine. But 1 000 000 repetitions of a 1 000-character string = 1 GB — which will crash most environments.
Rules of thumb:
- Keep output under 10 MB for in-browser use (avoids UI freezes)
- Keep output under 100 MB for server-side use (avoids OOM)
- For very large outputs, stream instead of building in memory:
// Node.js: write 1 GB to a file without holding it in RAM
const { createWriteStream } = require("fs");
const out = createWriteStream("big.txt");
const line = "test data line\n";
for (let i = 0; i < 1_000_000; i++) {
out.write(line);
}
out.end();
Unicode Safety
Repeating most text is safe. Two edge cases:
1. Emoji with combining characters (ZWJ sequences)
These are single visible characters composed of multiple Unicode code points. Repeating them works fine because you're repeating the whole sequence — as long as you treat the string as a sequence of characters, not bytes.
emoji = "👨👩👧" # 8 code points, 1 visible character
print(emoji * 3) # "👨👩👧👨👩👧👨👩👧" — correct
2. Combining diacritics
A letter like é may be one code point (U+00E9) or two (e + combining accent U+0301). Repeating either form works correctly. Problems only arise if you later count characters — use Unicode normalization first if the exact count matters.
Common Pitfalls
| Pitfall | What happens | Fix |
|---|---|---|
| Trailing separator | "a, a, a," instead of "a, a, a" |
Use join instead of loop + append |
| Off-by-one | Repeat 3 times means 3 copies, not 2 gaps | join(sep) of [text] * 3 gives 3 copies, 2 separators — correct |
| Huge output crash | 1M × 1 KB = 1 GB in RAM | Cap output size; stream to file for large data |
| Byte repeat vs char repeat | PHP str_repeat on multi-byte strings is safe; but substr + manual loop is not |
Use str_repeat (operates on bytes, safe for repetition); never split mid-codepoint |
| Separator included in text | repeatText("a, ", 3, ", ") → "a, , a, , a, " |
Strip trailing separator from text unit before repeating |
FAQ
What's the fastest way to repeat a string in JavaScript?"text".repeat(n) is the fastest for no-separator cases — it's a native engine operation. For separators, Array(n).fill(text).join(sep) is idiomatic and fast enough for any realistic output size.
How do I repeat a string with a newline in Python?"\n".join(["line"] * 10) — produces 10 copies separated by newlines, with no trailing newline.
Can I repeat multi-line text?
Yes — just put the multi-line block in the text variable and pick a separator. If each repetition should be a separate section, use "\n\n" as the separator.
What's the max output size for a browser tool?
Practically, keep the rendered output under 10 MB. Most browsers handle 5 million characters in a <textarea> without issues; beyond that you risk UI jank. Server-side there's no hard limit, but stay mindful of memory.
How do I repeat text a random number of times?
Generate a random integer in your target range first, then pass it to your repeat function:
const n = Math.floor(Math.random() * 10) + 1; // 1–10
const result = "ping".repeat(n);
How is this different from lorem ipsum?
Lorem ipsum generates realistic-looking placeholder prose in Latin. Repeating text generates an exact, predictable pattern — useful for character-limit testing, data pipelines, and anywhere you need a controlled, deterministic input rather than random prose.