Using String.Replace() with RegEx

Published June 28, 2021, Modified June 30, 2021

String.Replace()

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

1const str = 'I like cats'
2const newStr = str.replace('I', 'We')
3console.log(newStr)
4//We like cats
5

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:

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

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:

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

Wrapping Up

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

author image

Hi, I'm Leo Cuéllar. I'm a Software Engineer, technical interviewer, and technical writer. I'm also the founder of Devcore. I enjoy writing about front-end and job interview topics.

🌌 Join the Devcore

Subscribe and receive a weekly email with the most popular articles about modern front-end web development, the latest interview questions and the most relevant job opportunities.

No spam. Unsubscribe anytime.