How to remove/replace multiple occurrences of a particular word from a string?

How to remove/replace multiple occurrences of a particular word from a string?
Photo by Sam Pak / Unsplash

Find and replace is one of the most common use cases in IDE, but while writing code we would also come across use cases when we want to replace or remove a given set of characters from a string.

JavaScript is a bit notorious in this regard, it can be a bit daunting to replace multiple occurrences at one shot. Let us see few of the possible options for performing this operation.

  • split and join -  This has been my go-to solution for most of the time, since it's simple to understand and would work always.
let rawString = 'This is **raw **text';
let removedString = rawString.split('**').join('');
// This is raw text

let replaceString = rawString.split('**').join('%%');
// This is %%raw %%text
  • replace - Replace might be the first thing which most of the developers would use, but the caveat is, replace works only for the first occurrence, instead, you should be using the global flag in the replace string.
let rawString = 'This is **raw **text';
let removedString = string.replace(/\**/g, '');
// This is raw text

let replaceString = rawString.replace('\*\*/g').join('%%');
// This is %%raw %%text