Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. JavaScript
  3. JavaScript 参考
  4. JavaScript 标准内置对象
  5. String
  6. String.prototype.replaceAll()

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

String.prototype.replaceAll()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2020年8月⁩.

replaceAll() 方法返回一个新字符串,其中所有匹配pattern 的部分都被替换为replacementpattern 可以是一个字符串或一个RegExpreplacement 可以是一个字符串或一个在每次匹配时调用的函数。原始字符串保持不变。

尝试一下

const paragraph = "I think Ruth's dog is cuter than your dog!";console.log(paragraph.replaceAll("dog", "monkey"));// Expected output: "I think Ruth's monkey is cuter than your monkey!"// Global flag required when calling replaceAll with regexconst regex = /Dog/gi;console.log(paragraph.replaceAll(regex, "ferret"));// Expected output: "I think Ruth's ferret is cuter than your ferret!"

语法

js
replaceAll(pattern, replacement)

参数

pattern

可以是一个字符串或一个具有Symbol.replace 方法的对象,典型的例子是正则表达式。任何没有Symbol.replace 方法的值都将被强制转换为字符串。

如果pattern是一个正则表达式,则必须设置全局(g)标志,否则会抛出TypeError

replacement

可以是一个字符串或一个函数。替换字符串的语义与String.prototype.replace() 相同。

返回值

返回一个新字符串,其中所有匹配pattern 的部分都被替换为replacement

异常

TypeError

如果pattern 是一个正则表达式,并且没有设置全局(g)标志(其flags 属性不包含"g"),则会抛出该异常。

描述

该方法不会修改调用它的字符串。它返回一个新字符串。

replace() 不同,该方法将替换所有匹配的字符串,而不仅仅是第一个。如果字符串不是静态已知的,那么这特别有用,因为调用RegExp() 构造函数而不转义特殊字符可能会意外地改变它的语义。

js
function unsafeRedactName(text, name) {  return text.replace(new RegExp(name, "g"), "[REDACTED]");}function safeRedactName(text, name) {  return text.replaceAll(name, "[REDACTED]");}const report =  "A hacker called ha.*er used special characters in their name to breach the system.";console.log(unsafeRedactName(report, "ha.*er")); // "A [REDACTED]s in their name to breach the system."console.log(safeRedactName(report, "ha.*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system."

如果pattern 是一个具有Symbol.replace 方法的对象(包括RegExp 对象),则该方法将被调用,并以目标字符串和replacement 作为参数。它的返回值成为replaceAll() 的返回值。在这种情况下,replaceAll() 的行为完全取决于[Symbol.replace]() 方法,因此除了额外的输入验证(即正则表达式必须是全局的)之外,它将具有与replace() 相同的结果。

如果pattern 是一个空字符串,则替换内容将插入到每个 UTF-16 码元之间,类似于split() 的行为。

js
"xxx".replaceAll("", "_"); // "_x_x_x_"

有关正则表达式属性(尤其是sticky 标志)如何与replaceAll() 交互的更多信息,请参阅RegExp.prototype[Symbol.replace]()

示例

使用 replaceAll()

js
"aabbcc".replaceAll("b", ".");// 'aa..cc'

非全局正则表达式抛出错误

使用正则表达式搜索值时,它必须是全局的。下面的代码是不可行的:

js
"aabbcc".replaceAll(/b/, ".");// TypeError: replaceAll must be called with a global RegExp

下面的代码可以正常运行:

js
"aabbcc".replaceAll(/b/g, ".");("aa..cc");

规范

Specification
ECMAScript® 2026 Language Specification
# sec-string.prototype.replaceall

浏览器兼容性

参见

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp