How to Use replaceAll in JavaScript
Replacing every match in a string with the replaceAll method.
There are times when you need to replace every occurrence of something in a
string, like stripping the dashes out of a phone number. The replace method
looks like it should do this, but when you pass it a string it only replaces the
first match:
"1-800-555-0199".replace("-", "") // "1800-555-0199"
The good news is there's now a method built for exactly this: replaceAll.
The Old Way
Until recently you had two options. A regular expression with the g (global)
flag:
"1-800-555-0199".replace(/-/g, "") // "18005550199"
Or split and join:
"1-800-555-0199".split("-").join("") // "18005550199"
Both work, but neither says what you mean very clearly.
Using replaceAll
replaceAll replaces every match:
"1-800-555-0199".replaceAll("-", "") // "18005550199""I like cats. Cats are great.".replaceAll("cats", "dogs")// "I like dogs. Cats are great."
Matching is case-sensitive, so "Cats" isn't replaced. Like replace, it
returns a new string and leaves the original alone.
replaceAll is part of ES2021 and works in Chrome 85+, Firefox 77+, Safari
13.1+ and Node 15+.
No Escaping Needed
With a string, every character is matched literally. With a regular expression,
characters like +, . and $ have special meanings and need escaping:
"1+1+1".replace(/\+/g, " plus ") // "1 plus 1 plus 1""1+1+1".replaceAll("+", " plus ") // "1 plus 1 plus 1"
Using a Function
Instead of a string, you can pass a function. It's called with each match, and whatever it returns is used as the replacement:
"hello world".replaceAll("o", (match) => match.toUpperCase())// "hellO wOrld"
Using a Regular Expression
You can still pass a regular expression to replaceAll, but it has to have the
g flag:
"snake_case-and-kebab".replaceAll(/[-_]/g, " ")// "snake case and kebab""snake_case-and-kebab".replaceAll(/[-_]/, " ")// TypeError: replaceAll must be called with a global RegExp
For plain text, pass a string and skip the regular expression altogether.
Have some feedback on this post? .