找到你要的答案

Q:How can I make a regular expression that contains special characters, like word boundaries, with a variable?

Q:我怎样做一个正则表达式,包含特殊字符,如单词边界,与一个变量?

In Javascript, I am trying to write a regular expression that will match a word that is contained in a variable, but only when the word is a whole word. I wanted to do this by using word boundaries, like this:

var data = 'In this example of data, word has to be replaced by suggestion, but newword must not be replaced';
var item = {word: 'exampleWord', suggestion: 'suggestion'}
var word = "\b"+item.word+"\b";
var suggestion = item.suggestion;
var re = new RegExp(word, "gi");
data = data.replace(re, suggestion);

However, constructing a regular expression in this fashion apparently does not work. Can anyone suggest a way to construct this regular expression containing the variable and the word boundaries?

在JavaScript中,我试图写一个正则表达式将匹配一个单词包含一个变量,但只有当这个词是一个完整的词。我想用词界来做这个,像这样:

var data = 'In this example of data, word has to be replaced by suggestion, but newword must not be replaced';
var item = {word: 'exampleWord', suggestion: 'suggestion'}
var word = "\b"+item.word+"\b";
var suggestion = item.suggestion;
var re = new RegExp(word, "gi");
data = data.replace(re, suggestion);

然而,以这种方式构建正则表达式显然不起作用。有谁能提出一种方法来构造这个包含变量和单词边界的正则表达式吗?

answer1: 回答1:

You should use double escaped \\b:

var word = "\\b"+item.word+"\\b";

In case your item.word may contain special characters, use the RegExp.escape function.

var word = "PRICE: $56.23"
RegExp.escape= function(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
alert("\\b"+RegExp.escape(word)+"\\b");

你应该使用双重逃脱:

var word = "\\b"+item.word+"\\b";

如果你的item.word可能包含特殊字符,使用regexp.escape功能。

var word = "PRICE: $56.23"
RegExp.escape= function(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
alert("\\b"+RegExp.escape(word)+"\\b");
javascript  regex