Skip to content

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('')
→ 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: