Javascript check for a whole word in a unicode string

454 Views Asked by At

What is the correct way to check for a whole word in a unicode string in Javascript.

This works for ASCII only:

var strHasWord = function(word, str){
   return str.match(new RegExp("\\b" + word + "\\b")) != null;
};

I tried XRegExp as follows but this does not work either.

var strHasWord = function(word, str){
  // look for separators/punctuation characters or if the word is the first or the last in the string
  var re = XRegExp("(\\p{Z}|\\p{P}|^)" + word + "(\\p{Z}|\\p{P}|$)");
  return re.test(str);
  //return str.match(re);
}

Any suggestions. Thanks.

EDIT 1 The following seems to do the trick.

var function strHasWord = function(word, str){
 var re = RegExp("(\\p{Z}|\\p{P}|^)" + word + "(\\p{Z}|\\p{P}|$)", "u");
   return str.match(re) != null;
    //return re.test(str);
}
0

There are 0 best solutions below