How to replace all occurrences of strings in JavaScript

Find out the correct way to replace all occurrences of strings in pure JavaScript, from regular expressions to other methods


Use regular expressions

This simple regular expression will accomplish the following tasks:

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

This executes acase sensitiveSubstitution.

This is an example where I replaced all occurrences of the word "dog" in the stringphrase:

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, useiOptions in regular expressions:

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 cannot be used with regular expressions, so it is recommended to use this function to escape the string (taken fromMDN):

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

Use split and join

Although slower than regular expressions, another solution is to use two JavaScript functions.

first of allsplit(), It truncates the string when it finds a pattern (case sensitive) and returns an array with tokens:

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

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

Then, concatenate the token into the new string, this time without any separators:

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

wrap up:

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

Download mine for freeJavaScript beginner's manual


More js tutorials: