I have a searching system that splits the keyword into chunks and searches for it in a string like this:
var regexp_school = new RegExp("(?=.*" + split_keywords[0] + ")(?=.*" + split_keywords[1] + ")(?=.*" + split_keywords[2] + ").*", "i");
I would like to modify this so that so that I would only search for it in the beginning of the words.
For example if the string is:
"Bbe be eb ebb beb"
And the keyword is: "be eb"
Then I want only these to hit "be ebb eb"
In other words I want to combine the above regexp with this one:
var regexp_school = new RegExp("^" + split_keywords[0], "i");
But I’m not sure how the syntax would look like.
I’m also using the split function to split the keywords, but I don’t want to set a length since I don’t know how many words there are in the keyword string.
split_keywords = school_keyword.split(" ", 3);
If I leave the 3 out, will it have dynamic length or just length of 1? I tried doing a
alert(split_keywords.lenght);
But didn’t get a desired response
You should use the special word boundary character
\bto match the beginning of a word. To create the expression for an arbitrary number of keywords, you can generate it in a loop.I’m not sure about performance, but you can also consider to use
indexOfto test whether a substring is contained in a string.Update:
If
\bdoes not work for you (because of other “special” characters), and all your words are separated by a white space, you can useor
But for this to work you have to prepend the text you are searching in with a white space:
or you are write a more complex expression: