I am working on regex for searching hotel list. There are names like “testing hotel plaza”, “testing2 newhotel plaza”, “plaza hotel”….
Basically my requirement is if user type plaza then all the hotels should populate which contains “Plaza”… but if user types “aza” no result should populate. In short in given string I need to find is there any word that start with user entered string and if yes, then display the result.
Here is a code that I am stuck and is not working.
var regex = new RegExp("/\b"+searchString, "gi");
if (mainString.match(regex))
{
return true;
}
This is working but it is finding all occurrences even if it is a middle character or at any position which I do not want.
var regex = new RegExp(searchString , "gi");
if (mainString.match(regex))
{
return true;
}
When invoking the
RegExpconstructor like this, the regex is not enclosed in slashes (/.../), but you have a leading forward slash in your string. Also, escape sequence backslashes need to be escaped themselves, so what you should be using isEDIT:
Yes, since
\bis defined relative to[A-Za-z0-9_], this is indeed problematic when it comes to non-ASCII chars. You could probably solve it using more or less complicated lookarounds, but a much easier solution which would most likely do the trick here is to say thatsearchStringshould be found either at the beginning or after a whitespace character: