String.prototype.replaceAll()
String
值的 replaceAll()
方法返回一个新字符串,其中 pattern
的所有匹配项均替换为 replacement
。pattern
可以是字符串或 RegExp
,replacement
可以是字符串或每次匹配时调用的函数。原始字符串保持不变。
¥The replaceAll()
method of String
values returns a new string with all matches of a pattern
replaced by a replacement
. The pattern
can be a string or a RegExp
, and the replacement
can be a string or a function to be called for each match. The original string is left unchanged.
Try it
语法
参数
¥Parameters
pattern
-
可以是字符串或具有
Symbol.replace
方法的对象 - 典型示例是 正则表达式。任何不具有Symbol.replace
方法的值都将被强制转换为字符串。 replacement
-
: 可以是字符串或函数。替换的语义与
String.prototype.replace()
相同。
返回值
例外情况
描述
¥Description
此方法不会改变它所调用的字符串值。它返回一个新字符串。
¥This method does not mutate the string value it's called on. It returns a new string.
与 replace()
不同,此方法将替换所有出现的字符串,而不仅仅是第一个字符串。如果字符串不是静态已知的,这尤其有用,因为在不转义特殊字符的情况下调用 RegExp()
构造函数可能会无意中更改其语义。
¥Unlike replace()
, this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the RegExp()
constructor without escaping special characters may unintentionally change its semantics.
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()
相同的结果(除了正则表达式是全局的额外输入验证之外)。
¥If pattern
is an object with a Symbol.replace
method (including RegExp
objects), that method is called with the target string and replacement
as arguments. Its return value becomes the return value of replaceAll()
. In this case the behavior of replaceAll()
is entirely encoded by the [Symbol.replace]()
method, and therefore will have the same result as replace()
(apart from the extra input validation that the regex is global).
如果 pattern
是空字符串,则替换将插入到每个 UTF-16 代码单元之间,类似于 split()
行为。
¥If the pattern
is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to split()
behavior.
"xxx".replaceAll("", "_"); // "_x_x_x_"
有关正则表达式属性(尤其是 sticky 标志)如何与 replaceAll()
交互的更多信息,请参阅 RegExp.prototype[Symbol.replace]()
。
¥For more information about how regex properties (especially the sticky flag) interact with replaceAll()
, see RegExp.prototype[Symbol.replace]()
.
示例
使用 replaceAll()
非全局正则表达式抛出
规范
Specification |
---|
ECMAScript Language Specification # sec-string.prototype.replaceall |
浏览器兼容性
BCD tables only load in the browser