Javascript replace all strings

replace+g

The replace() function in JavaScript can accept a regular expression as the first parameter and use the second parameter to replace the text that matches the regular expression. Therefore, regular expressions can be used to match multiple strings and replace them with the corresponding replacement text.

let str = "Today I had an apple apple apple apple.";  
let newStr = str.replace(/apple/g, "fruit");  
console.log(newStr);

Here, setting the matching mode of the regular expression to g (global mode) can replace all strings.

replaceAll

JavaScript's String.prototype.replaceAll()methods can replace multiple strings at once. This method accepts two parameters: the first parameter is a regular expression or string representing the text to be replaced; the second parameter is a replacement text or function to replace the matched text.

let str = "Today I had an apple apple apple apple.";  
let newStr = str.replaceAll("apple", "fruit");  
console.log(newStr);

reference

https://www.imangodoc.com/f5b119f1.html

Guess you like

Origin blog.csdn.net/lilongsy/article/details/131834286