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?
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?
Share Improve this question edited May 29, 2017 at 20:04 Badacadabra 8,4977 gold badges31 silver badges54 bronze badges asked Aug 27, 2015 at 4:21 Snow FoxSnow Fox 4091 gold badge7 silver badges15 bronze badges 03 Answers
Reset to default 10Use 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
Use word boundary \b
for limiting the search to words.
Because @
is special character, you need to match it outside of the word.
\b
assert position at a word boundary (^\w|\w$|\W\w|\w\W)
, since \b
does not include special characters.
var str = "@devtest11 @devtest1";
str = str.replace(/@devtest1\b/g, "aaaa");
document.write(str);
If your string always starts with @
and you don't want other characters to match
var str = "@devtest11 @devtest1";
str = str.replace(/(\s*)@devtest1\b/g, "$1aaaa");
// ^^^^^ ^^
document.write(str);
\b
won't work properly if the words are surrounded by non space characters..I suggest the below method
var output=str.replace('(\s|^)@devtest1(?=\s|$)','$1aaaa');