admin管理员组文章数量:1243097
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');
本文标签: JavaScript regex to replace a whole wordStack Overflow
版权声明:本文标题:JavaScript regex to replace a whole word - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740173306a2235944.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论