user1956570
user1956570

Reputation: 142

jQuery filter function regexp

Can somebody explain why my elements aren't filtering?

this what wrote in a book, and he sad that if false element will be remove and will displayed elements with true :

$('li').filter(function() { return this.innerHTML.match(/^\d+$/)})

I need to filter only li with 14.15 (i want result just li with 14.15)!

http://jsfiddle.net/crew1251/MYXYX/

<ul id="list">
    <li>raz</li>
    <li>asdf 14.15</li>
    <li>tri</li>
    <li>chetire_Tri</li>
    <li>pyat</li>


</ul>


$('li').filter(function () {
    return this.innerHTML.match(/^\d+$/);
});

Upvotes: 0

Views: 7234

Answers (2)

Ruan Mendes
Ruan Mendes

Reputation: 92274

If you want to find the lis that contain digits, you should do the following

var listWithDigits = $('li').filter(function () {
    return this.innerHTML.match(/\d+/);
    // return this.innerHTML.match(/\d+$/); // returns lis that end with digits
    // return this.innerHTML.match(/^\d+/); // returns lis that start with digits
    // return this.innerHTML.match(/^\d+$/); // returns lis that contain only digits
});
console.log(listWithDigits.length); // 1

Your current regex is failing because it only accepts lis that contain only digits, because you've wrapped your regex with ^$

http://jsfiddle.net/MYXYX/1/

Upvotes: 6

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

You use a wrong pattern, you must remove anchors:

$('li').filter(function () {
    return $(this).html().match(/\d/);
});

Note that you don't need to test more than one digit, thus the + quantifier is useless.

Upvotes: 1

Related Questions