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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With