1

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?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Eva
  • 313
  • 1
  • 6
  • 17

1 Answers1

4

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");
Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563