2

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.

1

3 Answers 3

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

That worked perfect. Thanks so much.
2

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)

1 Comment

Thanks Esqew. Always happy to learn something new.
2

on the new version of nodejs(15+) you got String.replaceAll() function

'mystring'.replaceAll('string', 'str');

1 Comment

I noticed that, but Im scared of updating node and having some type of incompatibility with the existing code! Thanks Talg123.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.