replaceAll
是 JavaScript 中的一个字符串方法,用于将字符串中的所有匹配项替换为指定的值。这个方法在 ES2021(也称为 ES12)中被添加到 JavaScript 中,因此在使用时需要确保你的环境支持这个特性。
replaceAll
方法接受两个参数:
replace
方法配合全局正则表达式,replaceAll
提供了更简洁的语法。searchValue
是一个普通字符串时。searchValue
是一个正则表达式时。let text = "apple banana apple orange";
let newText = text.replaceAll("apple", "pear");
console.log(newText); // 输出: "pear banana pear orange"
let text = "apple123 banana456 apple789";
let newText = text.replaceAll(/\d+/g, "");
console.log(newText); // 输出: "apple banana apple"
replaceAll
方法如果你在一个不支持 ES2021 的环境中工作,可能会遇到 replaceAll
方法不被识别的问题。
解决方法:
replaceAll
方法的支持。replace
方法配合全局正则表达式。if (!String.prototype.replaceAll) {
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
}
let text = "apple banana apple orange";
let newText = text.replaceAll("apple", "pear");
console.log(newText); // 输出: "pear banana pear orange"
通过这种方式,即使在不支持 replaceAll
的环境中,也可以实现相同的功能。
领取专属 10元无门槛券
手把手带您无忧上云