- String.prototype.replaceAll()
- Try it
- Syntax
- Parameters
- Return value
- Exceptions
- Description
- How to replace all occurrences of a string in JavaScript?
- Splitting and Joining the Array
- Syntax
- Example
- With Global Regular Expression using replace() Method
- Syntax
- Example
- Using the replaceAll() method of Strings in JavaScript
- Syntax
- Example
- Conclusion
- 3 Ways To Replace All String Occurrences in JavaScript
- Table of Contents
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]() .
How to replace all occurrences of a string in JavaScript?
This tutorial will teach us how to replace all occurrences of a string in JavaScript which mean by the end of the tutorial we will learn to detect a given type of substring from the given string and replace it will another given string by the user.
To replace all occurrences of a string in JavaScript we have three methods which we are going to see in this tutorial, they are: splitting the string into an array and then joining it back by adding replacement in gaps, with the global regular expression using the replace() method, and at last we will see the replaceAll() method of the strings in JavaScript.
Splitting and Joining the Array
The idea behind this method is to find the required substring from the string and then split the other parts and store them in an array after that join all the parts and add the given replacement between them and convert it back to a string.
Syntax
Let’s look into its syntax −
const given_string; const to_replace; const replacement; const string_after_splitting = given_string.split(to_replace); const required_string = string_after_splitting.join(replacement);
In the above syntax, we have declared the three strings one is a string in which we want to perform replacements, the second is a string which we want to replace, and the last one is a string that will be the replacement for the string to replace.
After that, we used the split() method to split ‘given_string’ and stored its value in the array ‘string_after_splitting’. At last, we joined the elements of the array using the ‘join’ method and gave a ‘replacement’ string, and stored it in the ‘required_string’ variable (which is our required final answer/string).
Example
Let’s implement the above syntax in an example to get more understanding of it −
!DOCTYPE html> html> body> h3>Please press the button to replace and get the final string after replacement./h3> input type = "button" onclick = "replace()" value = "Press me"> /body> script> function replace() const given_string = "In this string, every a is going to be a large a"; const to_replace = 'a'; const replacement = 'A'; const string_after_splitting = given_string.split(to_replace); const required_string = string_after_splitting.join(replacement); document.write("Previous string was: " + given_string+ "
"+"After replacement string is: " + required_string) > /script> /html>
With Global Regular Expression using replace() Method
This method is the application of the string replace() function. In this method, we will declare the string to replace as a regular expression with global scope and will search and replace it with the provided string for replacement.
Syntax
Let’s see its syntax and understand how it works −
const given_string; const to_replace = new RegExp(to_replace_string, 'g'); const replacement; const required_string = given_string.replace(to_replace, replacement);
Example
Let’s implement the above syntax in an example to get more understanding of it −
!DOCTYPE html> html> body> h3>Please press the button to replace and get the final string after replacement./h3> input type = "button" onclick = "replace()" value = "Press me"> /body> script> function replace() const given_string = "In this string, every a is going to be a large a"; const to_replace = new RegExp('a','g'); const replacement = 'A'; const required_string = given_string.replace(to_replace, replacement); document.write("Previous string was: " + given_string+ "
" + "After replacement string is: " + required_string) > /script> /html>
Using the replaceAll() method of Strings in JavaScript
This method is similar to the replace() method but the only difference is there we were using the regular expression and here we used a simple string to replace. Let’s directly move to the syntax and understand its working in deep.
Syntax
const given_string; const to_replace; const replacement; const required_string = given_string.replaceAll(to_replace, replacement);
In the above syntax, we have declared the three strings one is a string in which we want to perform replacements, the second is the string which we want to replace, and the last one is a string that will be the replacement for the string to replace.
After that, we used the replaceAll() method to replace all occurrences of the given string with the provided string as replacement.
Example
Let’s implement the above syntax in an example to get more understanding of it −
!DOCTYPE html> html> body> h3>Please press the button to replace and get the final string after replacement./h3> input type = "button" onclick = "replace()" value = "Press me"> /body> script> function replace() const given_string = "In this string, every a is going to be a large a"; const to_replace = 'a'; const replacement = 'A'; const required_string = given_string.replaceAll(to_replace, replacement); document.write("Previous string was: " + given_string+ "
"+"After replacement string is: " + required_string); > /script> /html>
Conclusion
In this tutorial, we have learned how to replace all occurrences of a string in JavaScript. We have learned to detect a given type of substring from the given string and to replace it will another given string the user.
To replace all occurrences of a string in JavaScript there are three methods − splitting the string into an array and then joining it back by adding replacement in gaps, with the global regular expression using the replace() method, and at last the replaceAll() method of the strings in JavaScript.
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!