Replace a substring with special characters

Viewed 79

I have a string that contains some substrings wrapped in some special characters. Here's my code:

var p = 'The quick brown fox jumps over the lazy [dog]. If the [dog] reacted, was it really lazy?';

var regex = /[\\[dog\\]]/g;

console.log(p.replace(regex, 'ferret'));

The code gives me output The quick brown fox jumps over the lazy ferretdogferret. If the ferretdogferret reacted, was it really lazy? but I am expecting The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?

2 Answers

Just remove the character set around the whole pattern, and just match \[dog\]:

var p = 'The quick brown fox jumps over the lazy [dog]. If the [dog] reacted, was it really lazy?';

var regex = /\[dog\]/g;

console.log(p.replace(regex, 'ferret'));

You could just use standard JS and approach it like below.

let txt = 'The quick brown fox jumps over the lazy [dog]. If the [dog] reacted, was it really lazy?'

let txt1 = txt.split(' ')
txt1.map((word, i) => word.includes('dog') ? txt1[i]='ferret':null )
let sentence = txt1.join(' ')

console.log(sentence)

Related