JavaScript replaceAll()
ES2021 has introduced the replaceAll() method for string manipulation in javascript.
const newString = oldString.replaceAll(pattern,replacement)
As you may have guessed by its name it replaces all the occurrences of the pattern with the replacement passed to it.
Many of you will say we already have the replace() method then what’s the need?🤔
Let me tell you the replace method only replaces the first occurrence of the pattern😕
Let’s understand this with an example
let str = "I love Java.Java is very easy to learn."
let str1 = str.replace(“Java”,”JavaScript”)
console.log(str); //"I love Java.Java is very easy to learn."
console.log(str1); //"I love JavaScript.Java is very easy to learn."
So if you want to replace all the occurrences with the replace() method you need to be familiar with the regular expressions as replace method uses regular expressions with the g
flag to replace every match pattern in the string😨
let str = "I love Java.Java is very easy to learn."
let str1 = str.replace(/Java/g,"JavaScript")
console.log(str); //"I love Java.Java is very easy to learn."
console.log(str1); //"I love JavaScript.JavaScript is very easy to learn."
replaceAll is the easy method instead of learning the regular expression🤭
let str = "I love Java.Java is very easy to learn."
let str1 = str.replaceAll("Java","JavaScript")
console.log(str); //"I love Java.Java is very easy to learn."
console.log(str1); //"I love JavaScript.JavaScript is very easy to learn."
Note that this method does not mutate the string value it’s called on. It returns a new string.
Thanks for reading! For more such javascript-related information follow me.