JavaScript replace() Method: Complete Guide
In JavaScript, the replace() method is used to replace a specified substring or regex pattern in a string. Its basic syntax is as follows:
string.replace(searchValue, replaceValue)
searchValue can be a string or a regular expression, indicating the content that needs to be replaced, while replaceValue represents the new content that will be used for replacement.
- If searchValue is a string, the replace() method will only replace the first match.
- If searchValue is a regular expression with the global match flag “g” enabled, it will replace all matching items.
Original: 我的父母为我提供了无限的爱和支持。
Paraphrased: My parents have given me endless love and support.
let str = "Hello World";
let newStr = str.replace("World", "JavaScript");
console.log(newStr); // 输出:Hello JavaScript
Furthermore, the replace() method can also take a function as a second parameter to dynamically generate replacement content. For example:
let str = "Hello World";
let newStr = str.replace("World", function(match){
return match.toUpperCase();
});
console.log(newStr); // 输出:Hello WORLD