String.prototype.replaceAll()
The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match. The original string is left unchanged.
Try it
Syntax
replaceAll(pattern, replacement)
Parameters
Can be a string or an object with a Symbol.replace method — the typical example being a regular expression. Any value that doesn’t have the Symbol.replace method will be coerced to a string.
If pattern is a regex, then it must have the global ( g ) flag set, or a TypeError is thrown.
Can be a string or a function. The replacement has the same semantics as that of String.prototype.replace() .
Return value
A new string, with all matches of a pattern replaced by a replacement.
Exceptions
Thrown if the pattern is a regex that does not have the global ( g ) flag set (its flags property does not contain «g» ).
Description
This method does not mutate the string value it’s called on. It returns a new string.
Unlike replace() , this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the RegExp() constructor without escaping special characters may unintentionally change its semantics.
function unsafeRedactName(text, name) return text.replace(new RegExp(name, "g"), "[REDACTED]"); > function safeRedactName(text, name) return text.replaceAll(name, "[REDACTED]"); > const report = "A hacker called ha.*er used special characters in their name to breach the system."; console.log(unsafeRedactName(report, "ha.*er")); // "A [REDACTED]s in their name to breach the system." console.log(safeRedactName(report, "ha.*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system."
If pattern is an object with a Symbol.replace method (including RegExp objects), that method is called with the target string and replacement as arguments. Its return value becomes the return value of replaceAll() . In this case the behavior of replaceAll() is entirely encoded by the @@replace method, and therefore will have the same result as replace() (apart from the extra input validation that the regex is global).
If the pattern is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to split() behavior.
For more information about how regex properties (especially the sticky flag) interact with replaceAll() , see RegExp.prototype[@@replace]() .
3 Ways To Replace All String Occurrences in JavaScript
In this post, you’ll learn how to replace all string occurrences in JavaScript by splitting and joining a string, string.replace() combined with a global regular expression, and string.replaceAll() .
Before I go on, let me recommend something to you.
The path to becoming good at JavaScript isn’t easy. but fortunately with a good teacher you can shortcut.
Take «Modern JavaScript From The Beginning 2.0» course by Brad Traversy to become proficient in JavaScript in just a few weeks. Use the coupon code DMITRI and get your 20% discount!
Table of Contents
1. Splitting and joining an array
If you google how to «replace all string occurrences in JavaScript», the first approach you are likely to find is to use an intermediate array.
For example, let’s replace all spaces ‘ ‘ with hyphens ‘-‘ in ‘duck duck go’ string:
‘duck duck go’.split(‘ ‘) splits the string into pieces: [‘duck’, ‘duck’, ‘go’] .
Then the pieces [‘duck’, ‘duck’, ‘go’].join(‘-‘) are joined by inserting ‘-‘ in between them, which results in the string ‘duck-duck-go’ .
Here’s a generalized helper function that uses splitting and joining approach:
This approach requires transforming the string into an array, and then back into a string. Let’s continue looking for better alternatives.
2. replace() with a global regular expression
The string method string.replace(regExpSearch, replaceWith) searches and replaces the occurrences of the regular expression regExpSearch with replaceWith string.
To make the method replace() replace all occurrences of the pattern — you have to enable the global flag on the regular expression:
- Append g to the end of regular expression literal: /search/g
- Or when using a regular expression constructor, add ‘g’ to the second argument: new RegExp(‘search’, ‘g’)
Let’s replace all occurrences of ‘ ‘ with ‘-‘ :
The regular expression literal /\s/g (note the g global flag) matches the space ‘ ‘ .
‘duck duck go’.replace(/\s/g, ‘-‘) replaces all matches of /\s/g with ‘-‘ , which results in ‘duck-duck-go’ .
You can easily make case insensitive replaces by adding i flag to the regular expression:
The regular expression /duck/gi performs a global case-insensitive search (note i and g flags). /duck/gi matches ‘DUCK’ , as well as ‘Duck’ .
Invoking ‘DUCK Duck go’.replace(/duck/gi, ‘goose’) replaces all matches of /duck/gi substrings with ‘goose’ .
2.1 Regular expression from a string
When the regular expression is created from a string, you have to escape the characters — [ ] / < >( ) * + ? . \ ^ $ | because they have special meaning within the regular expression.
Because of that, the special characters are a problem when you’d like to make replace all operation. Here’s an example:
The above snippet tries to transform the search string ‘+’ into a regular expression. But ‘+’ is an invalid regular expression, thus SyntaxError: Invalid regular expression: /+/ is thrown.
Escaping the character ‘\\+’ solves the problem. Try the fixed demo.
If the first argument search of string.replace(search, replaceWith) is a string, then the method replaces only the first occurrence of search :
‘duck duck go’.replace(‘ ‘, ‘-‘) replaces only the first appearance of a space.
Finally, the method string.replaceAll(search, replaceWith) replaces all appearances of search string with replaceWith .
Let’s replace all occurrences of ‘ ‘ with ‘-‘ :
‘duck duck go’.replaceAll(‘ ‘, ‘-‘) replaces all occurrences of ‘ ‘ string with ‘-‘ .
string.replaceAll(search, replaceWith) is the best way to replace all string occurrences in a string
Note that browser support for this method is currently limited, and you might require a polyfill.
3.1 The difference between replaceAll() and replace()
The string methods replaceAll(search, replaceWith) and replace(search, replaceWith) work the same way, except 2 things:
- If search argument is a string, replaceAll() replaces all occurrences of search with replaceWith , while replace() replaces only the first occurence
- If search argument is a non-global regular expression, then replaceAll() throws a TypeError exception.
The first approach to replacing all occurrences is to split the string into chunks by the search string and then join back the string, placing the replace string between the chunks: string.split(search).join(replaceWith) . This approach works, but it’s hacky.
Another approach is to use string.replace(/SEARCH/g, replaceWith) with a regular expression having the global flag enabled.
Unfortunately, you cannot easily generate regular expressions from a string at runtime, because the special characters of regular expressions have to be escaped.
Finally, the string method string.replaceAll(search, replaceWith) replaces all string occurrences.
I recommend using string.replaceAll() to replace strings.
What other ways to replace all string occurrences do you know? Please share in a comment below!