Kalish
Kalish

Reputation: 833

Find how many words are starting with given search string - Regex

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;
}

Upvotes: 0

Views: 166

Answers (1)

Gustav Barkefors
Gustav Barkefors

Reputation: 5086

When invoking the RegExp constructor 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 is

var regex = new RegExp("\\b"+searchString, "gi");

EDIT:

Yes, since \b is 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 that searchString should be found either at the beginning or after a whitespace character:

var regex = new RegExp("(?:^|\\s)"+searchString, "gi");

Upvotes: 1

Related Questions