0

I need to filter a list according to a search string. The whole thing must be case-insensitive.

As you can see in the snippet, the i flag for case-insensitivity works in a normal Jquery selector, but not in the filter selector. Is this a bug or is there something wrong with my code?

var searchString = 't';

// WORKS
$('li[data-number*="' + searchString + '" i]').css('border', '1px solid red');

// SAME SELECTOR BUT DOESN'T WORK
$('li').filter('li[data-number*="' + searchString + '" i]').css('background', 'lightcoral');
<ul>

  <li data-number="One">First</li>
  <li data-number="Two">Second</li>
  <li data-number="Three">Third</li>
  <li data-number="Four">Fourth</li>


</ul>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Tonald Drump
  • 1,227
  • 1
  • 19
  • 32

1 Answers1

1

The selector in the filter() method doesn't accept flags in the same way that a selector provided to the jQuery object constructor does.

The workaround is to provide a function to filter() which you can use to convert the strings to the same case before comparison:

var searchString = 't';

$('li').filter(function() {
  return $(this).data('number').toLowerCase().indexOf(searchString) != -1;
}).css('background', 'lightcoral');
<ul>
  <li data-number="One">First</li>
  <li data-number="Two">Second</li>
  <li data-number="Three">Third</li>
  <li data-number="Four">Fourth</li>
</ul>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 2
    I'm sure you're right but that's quite weird. – Pointy Aug 31 '18 at 16:09
  • I've never heard of a flags in selectors, and can't find any mention of it in the documentation. – Barmar Aug 31 '18 at 16:12
  • 1
    @Barmar https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors – j08691 Aug 31 '18 at 16:14
  • That's DOM selectors, not jQuery. Does jQuery get them automatically from the DOM? – Barmar Aug 31 '18 at 16:17
  • I believe the Sizzle engine will use whatever it can natively. Therefore it's possible that using flags in IE and Edge will break, as they don't support it. – Rory McCrossan Aug 31 '18 at 16:24
  • In fact, it does. Curiosity got the better of me and I just tested it in Edge. You get this error from the OPs first example: `SCRIPT5022: Syntax error, unrecognized expression: li[data-number*="t" i]` – Rory McCrossan Aug 31 '18 at 16:25