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); //🍏🍏🍏
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)
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); // 🍏🍏🥝🥝🍋🍋🍉🍉
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