repeat Duplicates Strings, Rejecting Bad Counts
Duplicate strings with repeat for indentation and separator lines: zero returns the empty string, while negative or infinite counts raise RangeError.
Code
// repeat 复制字符串 n 次
console.log("ab".repeat(3));
console.log("-".repeat(10));
// 0 次返回空串,负数或 Infinity 抛 RangeError
console.log("x".repeat(0) === "");
try {
"x".repeat(-1);
} catch (e) {
console.log("negative:", e.name);
}
try {
"x".repeat(Infinity);
} catch (e) {
console.log("infinity:", e.name);
}
// 实际用途:缩进与分隔线
function indent(level, text) {
return " ".repeat(level) + text;
}
console.log(indent(2, "nested item"));
// 构建固定宽度分隔符
const width = 20;
console.log("+".repeat(width + 2));Output
Captured from a sandboxed run of this snippet in the build pipeline.
ababab
----------
true
negative: RangeError
infinity: RangeError
nested item
++++++++++++++++++++++How the snippet works
Everything happens inside the function indent.
Caveats
- Everything it calls is documented as part of the language core.
Using it
Entry signature: function indent(level, text)
The run prints ab, negative:, infinity: — each prefix names the step that produced it.
Key statements
return " ".repeat(level) + text;
Interactive Tools for This Topic
Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.
FAQ
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `indent` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.