Skip to content

How to replace all occurrences of a string in JavaScript

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

I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter

  • C Handbook
  • Command Line Handbook
  • CSS Handbook
  • Express Handbook
  • Git Cheat Sheet
  • Go Handbook
  • HTML Handbook
  • JS Handbook
  • Laravel Handbook
  • Next.js Handbook
  • Node.js Handbook
  • PHP Handbook
  • Python Handbook
  • React Handbook
  • SQL Handbook
  • Svelte Handbook
  • Swift Handbook

JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list