How to Replace All Occurrences of a String in JavaScript
Learn the proper way to replace all occurrences of a string in plain JavaScript, including using regular expressions and other approaches.
Using a Regular Expression
To replace all occurrences of a string with another string, you can use a regular expression. This simple regex, String.replace(/<TERM>/g, '')
, will perform the task. Note that it is case sensitive.
Here’s an example that demonstrates replacing all occurrences of the word “dog” in the string phrase
:
1 | const phrase = 'I love my dog! Dogs are great'; |
If you want to perform a case-insensitive replacement, you can modify the regular expression to include the i
option: String.replace(/<TERM>/gi, '')
.
Here’s an example that shows replacing all occurrences of the word “dog” in a case-insensitive manner:
1 | const phrase = 'I love my dog! Dogs are great'; |
If your string contains special characters, remember to escape it using the escapeRegExp
function. This function escapes special characters in a string and allows for proper pattern matching. Here is the escapeRegExp
function:
1 | const escapeRegExp = (string) => { |
Using Split and Join
Another approach to replace all occurrences of a string is to use the split()
and join()
functions in JavaScript.
The split()
function splits a string into an array of tokens based on a specified pattern (case sensitive). You can then use the join()
function to join the tokens into a new string without any separator.
Here’s an example that demonstrates this approach:
1 | const phrase = 'I love my dog! Dogs are great'; |
In conclusion, you now know how to replace all occurrences of a string in JavaScript. Whether you choose to use regular expressions or the split()
and join()
functions, you have options for achieving your desired result.
tags: [“JavaScript”, “string replacement”, “regular expressions”, “split function”, “join function”]