Using String.Replace() with RegEx

The replace() method is often used in JavaScript to replace parts of a string. You may have been using it as follows:

const str = 'I like cats'
const newStr = str.replace('I', 'We')
console.log(newStr)
//We like cats

As you can see, the method basically accepts two parameters: the string to be replaced and the replacement.

In reality, that's actually a little more complicated. The first parameter accepts two options:

  1. A string to be replaced, as mentioned above
  2. A RegEx object or literal. The match will be replaced with the second parameter

The second parameter also accepts two options:

  1. The replacement string
  2. A function that will be invoked to create the replacement string

In most real-world cases you will be looking for patterns instead of fixed strings, so using a RegEx as the first parameter will be the solution to our problems.

Using Regex with replace()

Let's start with an example and then explain how it works:

const reg = / \((.*?)\)/
const str = 'The quick brown (some unwanted string) fox jumps over the (another unwanted string) lazy dog.'
const newStr = str.replace(reg, '')
console.log(newStr)
//The quick brown fox jumps over the (another unwanted string) lazy dog.

So what's happening? Well, in our case, anything between parenthesis (including the parenthesis) will match with our RegEx, so the replace() method will replace that with our replacement string ''.

There's still one flaw with our code. It's just replacing the first match, so in the case that we want to replace everything that matches our RegEx, we would just have to use the g flag in our RegEx:

const reg = / \((.*?)\)/g //<-- notice the flag
const str = 'The quick brown (some unwanted string) fox jumps over the (another unwanted string) lazy dog.'
const newStr = str.replace(reg, '')
console.log(newStr)
//The quick brown fox jumps over the lazy dog.

Wrapping Up

RegEx is a POWERFUL tool and it makes replacing strings in JavaScript a more effective task, to say the least.

This article was first published on devcore.io. go check it out!

16