replaceAll() 方法可在 JavaScript 字符串中全局替换指定子串,将所有匹配子串替换为给定的替换字符串。使用方式为 string.replaceAll(searchValue, replaceValue),其中 searchValue 是要被替换的子串,replaceValue 是要替换的新字符串。

JavaScript 中的 replaceAll() 用法
问题: JavaScript 中的 replaceAll() 方法有什么作用?
解答: replaceAll() 方法用于在字符串中全局替换指定子串。它将字符串中的所有匹配子串替换为给定的替换字符串。
使用方式:
string.replaceAll(searchValue, replaceValue);
其中:
-
string是要进行替换的原始字符串。 -
searchValue是要被替换的子串。 -
replaceValue是要替换子串的新字符串。
示例:
const str = "JavaScript is a popular programming language.";
// 将 "is" 替换为 "was"
const newStr = str.replaceAll("is", "was");
console.log(newStr); // 输出:"JavaScript was a popular programming language."注意: replaceAll() 方法只替换完全匹配的子串。例如,在以下示例中,a 不会被替换,因为 cat 不是字符串中的完全匹配子串:
const str = "The cat is on the mat.";
// 试图替换 "cat" 为 "dog"
const newStr = str.replaceAll("cat", "dog");
console.log(newStr); // 输出:"The cat is on the mat."要替换不完全匹配的子串,可以使用正则表达式和 replace() 方法。
优点:
- replaceAll() 方法提供了全局替换功能,无需使用循环或正则表达式。
- 它易于使用且易于理解。
缺点:
- 在需要替换不完全匹配的子串时,它可能不适用于某些情况。
- 对于较长的字符串,它可能会导致性能问题。










