Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing string multiple times on a variable with NODE.js

Tags:

node.js

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.

like image 751
Danielle Avatar asked Dec 31 '25 17:12

Danielle


1 Answers

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)
like image 170
Pyxel Codes Avatar answered Jan 02 '26 08:01

Pyxel Codes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!