Published June 28, 2021, Modified June 30, 2021
1const str = 'I like cats'2const newStr = str.replace('I', 'We')3console.log(newStr)4//We like cats5
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:
- A string to be replaced, as mentioned above
- A RegEx object or literal. The match will be replaced with the second parameter
The second parameter also accepts two options:
- The replacement string
- 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.
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 flag2const 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
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.