JS 字符串:replace / replaceAll / 正则替换

replace 只替换第一个;replaceAll/全局正则替换全部;支持函数替换与捕获组。

#resource / javascript #resource / ecmascript #type / concept #status / growing

[!info] related notes JavaScript / TypeScript 字符串方法 ECMAScript正则表达式

JS 字符串:replace / replaceAll / 正则替换

1) 一句话结论

  • replace(str, x):只替换第一个匹配
  • 想替换所有:优先 replaceAll,或正则 /.../g

2) replace vs replaceAll

"a-b-c".replace("-", "_");      // "a_b-c"
"a-b-c".replaceAll("-", "_");   // "a_b_c"

3) 正则全局替换

"a-b-c".replace(/-/g, "_"); // "a_b_c"

4) 函数替换(非常实用)

场景:需要动态生成替换内容,比如驼峰转短横线。

function camelToKebab(str: string): string {
  return str.replace(/[A-Z]/g, (ch) => "-" + ch.toLowerCase());
}

camelToKebab("backgroundColor"); // "background-color"

5) 捕获组替换(常见题)

const s = "2026-03-17";
const swapped = s.replace(/(\d{4})-(\d{2})-(\d{2})/, "$2/$3/$1");
// "03/17/2026"

6) 高频陷阱

  • replaceAll 的第一个参数如果是正则,必须带 g,否则会抛错(不同运行时提示略有差异)
  • 正则带 g 的状态问题不影响 String.prototype.replace 本身,但会影响你复用同一个 RegExp 对象去 test/exec(见 ECMAScript正则表达式
创建于 2026/3/16 更新于 2026/5/27