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.

JavascriptForm Validation

Code

javascriptsnippet
18 lines
// 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:00

How 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

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`.