C_K
C_K

Reputation: 1243

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 imagine, 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");
        }
    })
});

Upvotes: 1

Views: 181

Answers (2)

Matt Ball
Matt Ball

Reputation: 359786

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.

Upvotes: 1

flori
flori

Reputation: 15837

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')

Upvotes: 2

Related Questions