Skip to content

How to replace all occurrences of a string in JavaScript

New Course Coming Soon:

Get Really Good at Git

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('')
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: