replaceAll Replaces Every Occurrence
replaceAll rewrites every occurrence while replace stops after the first; a regex argument must carry the g flag or the call throws a TypeError.
Code
// replaceAll 换掉全部出现;replace 只换第一处
const raw = '2026-11-13 09:30-12:00';
console.log(raw.replaceAll('-', '_'));
console.log(raw.replace('-', '_'));
// 正则也能做替换对象,但必须带 g 标志,否则 replaceAll 直接抛错
const unified = raw.replaceAll(/[-\s]+/g, '_');
console.log(unified);
try {
raw.replaceAll(/-/, '_');
} catch (error) {
console.log('needs g flag:', error instanceof TypeError);
}
// 归一化结果再交给后续校验:按分隔符拆出字段
const fields = unified.split('_');
console.log('fields:', fields.length, '-', fields[0], '...', fields[fields.length - 1]);Output
Captured from a sandboxed run of this snippet in the build pipeline.
2026_11_13 09:30_12:00
2026_11-13 09:30-12:00
2026_11_13_09:30_12:00
needs g flag: true
fields: 5 - 2026 ... 12:00How the snippet works
Top-level bindings raw, unified, fields hold the demo state — nothing sits inside a function scope.
Applying it
Look for the needs g flag:, fields: prefixes when the file runs; they tie each line to its step.
Statements that matter
const unified = raw.replaceAll(/[-\s]+/g, '_');
const raw = '2026-11-13 09:30-12:00';
const fields = unified.split('_');
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free. Its state lives in module-level bindings: `raw`, `unified`, `fields`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.