If I have a string, e.g.: "Consensus IRIS 2010-11 Series 6"
If someone types part of that string, e.g. "iris" into a textbox, how can I identify the substring in the original string?
I have the following, but it only matches when the string starts with the value from the text box.
开发者_开发知识库var txt= $('#txtName').val();
var regExp = new RegExp("^" + txt, "i");
var t = item.name.replace(regExp, "<span class='matched-text'>" + txt + "</span>");
Side note: I am baffled by regular expressions!
Your problem comes from the fact that prepending "^"
to your regular expression makes it only match at the beginning of the string/text box. Remove that and it should work as expected for normal substrings.
However, if someone types a regular expression into the search box, your code could have unexpected effects. For example, if someone typed in \w
, every letter and number would be highlighted. This site is good for learning more about regular expressions.
Because your regular expression begins with ^
it will only match sequences that begin with whatever the value of txt
is. Remove the ^
and you're set.
Try with this:
var regExp = new RegExp(txt, "i");
Or this:
var regExp = new RegExp("\b"+txt"\b", "i");
The first will match txt
anywhere in the string, even in the middle of a word. The second will not match in the middle of a word.
精彩评论