String.prototype.replaceAll() translates this sentence into English
Overview of the String.prototype.replaceAll() Method
ECMAScript 2021 (ES12) introduced the String.prototype.replaceAll()
method, addressing a long-standing pain point in global string replacement. The traditional replace()
method was not intuitive when using regular expressions for global replacement, while the new method provides a more concise syntax.
Basic Syntax and Parameters
The method signature is as follows:
replaceAll(searchValue, replaceValue)
Parameter description:
searchValue
: Can be a string or a regular expression (must include theg
flag)replaceValue
: A replacement string or function
const str = "apple,orange,apple,banana";
console.log(str.replaceAll("apple", "kiwi"));
// Output: "kiwi,orange,kiwi,banana"
Differences from the replace() Method
The traditional replace()
method required regular expressions to replace all matches:
// Old method
const text = "foo bar foo";
text.replace(/foo/g, "baz"); // "baz bar baz"
// New method
text.replaceAll("foo", "baz"); // Same as above
Key differences:
replaceAll()
performs global replacement by default, without needing theg
flag- Different behavior when the first parameter is a string
- Improved readability and clearer intent
Using a String as the Search Value
When the first parameter is a string, all matching substrings are replaced:
const poem = "roses are red, violets are blue";
console.log(poem.replaceAll("are", "ARE"));
// Output: "roses ARE red, violets ARE blue"
Using a Regular Expression as the Search Value
When using a regular expression, the g
flag must be included; otherwise, a TypeError
is thrown:
const data = "ID: 123, ID: 456, ID: 789";
// Correct usage
console.log(data.replaceAll(/\d+/g, "***"));
// Output: "ID: ***, ID: ***, ID: ***"
// Incorrect usage (missing g flag)
// data.replaceAll(/\d+/, "***") will throw an error
Using a Function as the Replacement Value
The replacement value can be a function that returns a string, with parameters identical to replace()
:
const text = "Score: 80, Score: 90, Score: 100";
const result = text.replaceAll(/\d+/g, (match) => {
return parseInt(match) + 5;
});
console.log(result);
// Output: "Score: 85, Score: 95, Score: 105"
Special Replacement Patterns
Supports the same special replacement patterns as replace()
:
const names = "John Smith, Jane Doe";
console.log(names.replaceAll(/(\w+)\s(\w+)/g, "$2, $1"));
// Output: "Smith, John, Doe, Jane"
Practical Use Cases
Use Case 1: Batch Replacement of HTML Entities
function decodeHTMLEntities(text) {
const entities = {
"&": "&",
"<": "<",
">": ">",
""": "\"",
"'": "'"
};
let result = text;
for (const [entity, char] of Object.entries(entities)) {
result = result.replaceAll(entity, char);
}
return result;
}
Use Case 2: Template Variable Replacement
const template = "Hello {{name}}, your order {{orderId}} is ready";
const values = { name: "Alice", orderId: "12345" };
let result = template;
for (const [key, value] of Object.entries(values)) {
result = result.replaceAll(`{{${key}}}`, value);
}
console.log(result);
// Output: "Hello Alice, your order 12345 is ready"
Performance Considerations
For large-scale string replacement, regular expressions are generally more efficient than multiple string replacements:
// Slower implementation
let str = "a.b.c.d";
for (let i = 0; i < 1000; i++) {
str = str.replaceAll(".", "-");
}
// Faster implementation
str = "a.b.c.d".replaceAll(/\./g, "-");
Browser Compatibility and Polyfill
In environments without support, a polyfill can be implemented as follows:
if (!String.prototype.replaceAll) {
String.prototype.replaceAll = function(search, replace) {
if (search instanceof RegExp && !search.global) {
throw new TypeError("replaceAll called with non-global RegExp");
}
return this.replace(
search instanceof RegExp ? search : new RegExp(search, "g"),
replace
);
};
}
Comparison with Other Languages
Similar functionality in other languages:
- Python:
str.replace(old, new, count=-1)
- Java:
String.replace(CharSequence, CharSequence)
- C#:
Replace(string oldValue, string newValue)
JavaScript's implementation maintains consistency with other languages while offering the flexibility of regular expressions.
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:for-in机制标准化
下一篇:Promise.any()