5

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?

0

3 Answers 3

10

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
Sign up to request clarification or add additional context in comments.

7 Comments

\b is a bit tricky with the start though, imagine the input of: "!!@devtest1" and a pattern of /\b@devtest1\b/. There is no word-boundary between "!" and "@". (That is, the definition of word boundary is specific; but not always appropriate.)
Show what you tried. (As @user2864740 says, it won't work on the start; but then that is not what the example in the question had trouble with.)
@user2864740 So how can I do it?
"not successfully" is an useless bug report. If you have a failing test case, please report it, and what happens instead.
that would also match hello@devtest1 which is not what op would expect
|
1

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);

9 Comments

\b between @ and devtest1 is useless, as it will always match (the neighbours being constant).
@\bd is a bit useless; it is equivalent to @d. Putting a \b before @ is also problematic .. but it can be omitted for the sown data.
that would also match hello@devtest1
@Anirudha Check the other solution, now it wont
@Anirudha Kindly check again. I've updated answer not to remove spaces. Thanks for pointing out mistake
|
1

\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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.