开发者

Regular Expression: Match Partial or full string

I have small script that takes the value from a text input and needs to match an item in an array either partially or fully.

I'm struggling at the moment with the regular expression and the syntax and wondered if I could pick your brains.

for (var i=0; i < liveFilterData.length; i+=1) {

    if (liveFilterData[i].match(liveFilter.val())) {
        alert();
    }
}

I need the liveFilter.val() and Regular Expression to match the current array item liveFilterData[i] so if someone types in H or h in the text box, it checks if there is a matching item in the array. If they type in He or he then it matches Head, Header or heading.

Sorry, I've looked all over the web on how to build regular expressions but I c开发者_JS百科an't work it out.


Simple string comparison shold do the trick:

for (var v, i = liveFilterData.length; i--;) { 
    if (liveFilterData[i].slice (0, (v = liveFilter.val().toLowerCase ()).length) === v) {
        alert();
    }
}

liveFilterData should contain the words in lower case.


I'm not sure I totally understand the question. Is liveFilter.val() a regular expression, or is it just a string that you are trying to match against any value in an array? I'm guessing that you have a event on the textbox's keypress, keydown or keypress, and that the code you wrote above runs in the callback to this event. If so, there are a number of things you can do to convert the value to an appropriate regex: "^"+liveFilter.val(), Since you are using the regex in a loop, you should precompile it with new RegExp, so your loop would look something like:

//the i in the second param here is a flag indicating case insensitive
//a hat '^' in regex means 'beginning of the input'
regex = new RegExp("^"+liveFilter.val(), i);
for (var i=0; i < liveFilterData.length; i+=1) {
    // regex.test uses the precompiled regex, and determines if there is a match 
    if (regex.test(liveFilterData[i])) {
        alert("matched " + i);
    }
}

Hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜