简体   繁体   English

JavaScript 正则表达式替换整个单词

[英]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:我使用这种方式将@devtest1替换为另一个字符串:

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

However, its result ( aaaa1 aaaa ) is not what I expect.然而,它的结果( aaaa1 aaaa )并不是我所期望的。 The expected result is: @devtest11 aaaa .预期结果是: @devtest11 aaaa I just want to replace the whole word @devtest1 .我只想替换整个词@devtest1

How can I do that?我怎样才能做到这一点?

Use the \\b zero-width word-boundary assertion.使用\\b零宽度字边界断言。

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:如果您还需要防止匹配hello@devtest1 ,您可以这样做:

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.使用词边界\\b将搜索限制为单词。

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. \\b在单词边界(^\\w|\\w$|\\W\\w|\\w\\W)断言位置,因为\\b不包含特殊字符。

 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将无法正常工作..我建议使用以下方法

var output=str.replace('(\s|^)@devtest1(?=\s|$)','$1aaaa');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM