Eva
Eva

Reputation: 323

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

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?

Upvotes: 1

Views: 43

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627600

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

Upvotes: 4

Related Questions