Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript regex to replace a whole word

I have a variable:

var str = "@devtest11 @devtest1";

I use this way to replace @devtest1 with another string:

str.replace(new RegExp('@devtest1', 'g'), "aaaa")

However, its result (aaaa1 aaaa) is not what I expect. The expected result is: @devtest11 aaaa. I just want to replace the whole word @devtest1.

How can I do that?

like image 503
Snow Fox Avatar asked Dec 20 '22 00:12

Snow Fox


1 Answers

Use the \b zero-width word-boundary assertion.

var str = "@devtest11 @devtest1";
str.replace(/@devtest1\b/g, "aaaa");
// => @devtest11 aaaa

If you need to also prevent matching the cases like hello@devtest1, you can do this:

var str = "@devtest1 @devtest11 @devtest1 hello@devtest1";
str.replace(/( |^)@devtest1\b/g, "$1aaaa");
// => @devtest11 aaaa
like image 140
Amadan Avatar answered Dec 24 '22 02:12

Amadan