How to replace all occurrences of a string in JavaScript

Using a regular expression

This simple regex will accomplish the job:

String.replace(/<TERM>/g, '')

This is a very useful tool.Case-sensitive Substitution

Here’s an example: I have substituted all instances 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"

Use the  i  option to perform a case-insensitive replacement

String.replace(/<TERM>/gi, '')

Exemple

const phrase = 'I love my dog! Dogs are great'
const stripped = phrase.replace(/dog/gi, '')

stripped //"I love my ! s are great"

Be aware that strings containing special characters won’t work well with regular expressions. This is why it is suggested to escape the string by using the following function (taken directly from MDN).

const escapeRegExp = (string) => {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}

Using split and join

Two JavaScript functions are an alternative, but slower than the regex.

split(), is the first, which trims strings when it finds a pattern (case-sensitive) and returns an array containing the tokens.

const phrase = 'I love my dog! Dogs are great'
const tokens = phrase.split('dog')

tokens //["I love my ", "! Dogs are great"]

Next, join the tokens into a new string without any separator.

const stripped = tokens.join('') //"I love my ! Dogs are great"

Ending:

const phrase = 'I love my dog! Dogs are great'
const stripped = phrase.split('dog').join('')