Danielle
Danielle

Reputation: 1486

Replacing string multiple times on a variable with 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.

Upvotes: 0

Views: 597

Answers (3)

Talg123
Talg123

Reputation: 1506

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

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

Upvotes: 1

Pyxel Codes
Pyxel Codes

Reputation: 170

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)

Upvotes: 4

esqew
esqew

Reputation: 44707

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)

Upvotes: 2

Related Questions