I have a string variable where I have a text that needs to be replaced. This text appears several times.
For example:
let title="Hello [username], your name is [username]. Goodbye [username]"
and
myuser = "Danielle"
the following line does does the trick:
title = title.replace(/username/gi, myuser)
And this is the result I get:
Hello [Danielle], your name is [Danielle]. Goodbye [Danielle]
But what I really want to replace is [username], like this:
title = title.replace(/[username]/gi, myuser)
Which does not work.
I tried [username], "[username]", '[username]'... etc but nothing seems to work.
What am I doing wrong?
Thanks.
CodePudding user response:
the square bracket [
has a dedicated reason in a regex, therefore it has to be escaped
you escape a charachter, meaning ignore any usage of it and just use it as a "character" with a backslash \
try using
title = title.replace(/\[username\]/gi, myuser)
CodePudding user response:
When using a RegExp pattern for the first argument of String.replace()
, you have to escape any characters you’re looking to match that are also RegExp control characters.
Since square brackets have special meaning in RegExp, escape them with the appropriate escape sequence (prepended with the \
token):
title = title.replace(/\[username\]/gi, myuser)
CodePudding user response:
on the new version of nodejs(15 ) you got String.replaceAll() function
'mystring'.replaceAll('string', 'str');