What is the JavaScript replaceAll string method in ES2021?
If youβve worked with strings in JavaScript, then you may know about String.replace(searchString, replaceString), which searches for the first match of searchString, replaces that with replaceString, and then returns a new String.
let apple = "πππ";let newApple = apple.replace("π", "π");console.log(newApple); //"πππ"
The replace method only replaces the first match of the search string.
With the repaceAll method, we can replace all the matches of the search string.
let apple = "πππ";
let newApple = apple.replaceAll("π", "π");
console.log(newApple); //πππ
Syntax
replaceAll(regexp | searchString, replaceString | replacerFunction)
regex β searches in the source string. The regex should have the /g global flag, otherwise, it will throw an error.
searchString β string to be searched in the source string.
replaceString β string to be replaced in the place of the search string.
replacerFuntionβ the function that will be called on each match found. The source string will be replaced with the value returned from this function.
Using the syntax above, we can call the replaceAll method in four combinations.
replaceAll(regexp, replaceString)
replaceAll(regexp, replacerFunction)
replaceAll(searchString, replaceString)
replaceAll(searchString, replacerFunction)
Examples
let fruits = "ππππππππ";
// regex and replaceString
fruits = fruits.replaceAll(/π/g, "π");
console.log(fruits); // ππππππππ
// regex and replaceFunction
fruits = fruits.replaceAll(/π/g, ()=> {
return "π";
});
console.log(fruits); // ππππππππ
// replaceAll(searchString, replaceString)
fruits = fruits.replaceAll("π", "π");
console.log(fruits); // ππππππππ
// replaceAll(searchString, replacerFunction)
fruits = fruits.replaceAll("π", ()=> "π₯");
console.log(fruits); // πππ₯π₯ππππ
Using replacement patterns
When using replaceString, we can also pass some special replacement patterns:
οΌοΌ β replace the searchString with a single οΌ.
οΌ& β replace the searchString with matched substring.
**οΌ``** -- replace the searchString` with the substring before the matched string.
οΌ' β replace the searchString with the substring after the matched string.
// using $$
let st = "abc";
st.replaceAll("a", "$$"); // $bc
// using $&
let st = "abc";
st.replaceAll("a", "$&"); // abc
// using $`
let st = "abc";
st.replaceAll("c", "$`"); // abab
// using $'
let st = "abc";
st.replaceAll("a", "$'"); // bcbc
If you want to replace the string with special replacement patterns, then you can return the special replacement patterns inside the replacementFunction:
let st = "abc";
st = st.replaceAll("a",()=> "$$" );
console.log(st); // $$bc