How to replace all occurrences of a string in JavaScript
New Courses Coming Soon
Join the waiting lists
Find out the proper way to replace all occurrences of a string in plain JavaScript, from regex to other approaches
Using a regular expression
This simple regex will do the task:
String.replace(/<TERM>/g, '')
This performs a case sensitive substitution.
Here is an example, where I substitute all occurrences of the word ‘dog’ in the string phrase
:
const phrase = 'I love my dog! Dogs are great'
const stripped = phrase.replace(/dog/g, '')
stripped //"I love my ! Dogs are great"
To perform a case insensitive replacement, use the i
option in the regex:
String.replace(/<TERM>/gi, '')
Example:
const phrase = 'I love my dog! Dogs are great'
const stripped = phrase.replace(/dog/gi, '')
stripped //"I love my ! s are great"
Remember that if the string contains some special characters, it won’t play well with regular expressions, so the suggestion is to escape the string using this function (taken from MDN):
const escapeRegExp = (string) => {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
Using split and join
An alternative solution, albeit slower than the regex, is using two JavaScript functions.
The first is split()
, which truncates a string when it finds a pattern (case sensitive), and returns an array with the tokens:
const phrase = 'I love my dog! Dogs are great'
const tokens = phrase.split('dog')
tokens //["I love my ", "! Dogs are great"]
Then you join the tokens in a new string, this time without any separator:
const stripped = tokens.join('') //"I love my ! Dogs are great"
Wrapping up:
const phrase = 'I love my dog! Dogs are great'
const stripped = phrase.split('dog').join('')
Here is how can I help you:
- COURSES where I teach everything I know
- CODING BOOTCAMP cohort course - next edition in 2025
- THE VALLEY OF CODE your web development manual
- BOOKS 17 coding ebooks you can download for free on JS Python C PHP and lots more
- Interesting links collection
- Follow me on X