开发者

incremental regex filterer

I have a long list of <a> tags, and i'd like to filter through them live; that is, to remove the ones that don't match. I'd filter through them based on the text input in an input field. Regex would obviously search the a tag contents for a match to the input field, but i was wondering how to make it fancier, and actively filter the list like google's search bar does these days. I ima开发者_运维百科gine, a key up function would trigger the regex function.

The part i don't know how to do is this:

[input field]ArI[/]

List:

• ArIes
• ArIstotle

i.e., how to make it check the nth letter of the list item.

EDIT

This is what i have so far, and it doesn't work.

$("input.CardName_Input").keyup(function() {
    var getPhrase = $(".CardName_Input").val();

    new RegExp('^' + getPhrase + '.', 'i');

    $("#Results a").each(function() {
        if (!($(this).val().match(RegExp))) {
            $(this).addClass("HIDE");
        }
    })
});


As far as I understand you just have to check for the beginning of each list item string?

Then you could use something like /^Ar./i as expression?

In your case you could build the RegExp dynamically new RegExp('^' + searchString + '.', 'i')


This is what i have so far, and it doesn't work.

The code constructs a new RegExp but doesn't actually do anything with it. Then it passes RegExp (a function) to match. You need to assign the regexp to a variable so you can use it, and pass that to match:

$("input.CardName_Input").keyup(function ()
{
    var getPhrase = $(".CardName_Input").val(),
        re = new RegExp('^' + getPhrase + '.', 'i');

    $("#Results a").each(function ()
    {
        var $this = $(this);
        if (!$this.val().match(re)) $this.addClass("HIDE");
    })
});

N.B. if you don't want special characters in the .CardName_Input to break your code, you'll need to escape getPhrase.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜