Lets say I have some elements like this
<div class="friendListItem" data-user-name="Andi">Andi<div>
<div class="friendListItem" data-user-name="John">John<div>
<div class="friendListItem" data-user-name="Anderson">Anderson<div>
<div class="friendListItem" data-user-name="John Smith">John Smith<div>
<div class="friendListItem" data-user-name="George">George<div>
I am trying to make a search functionality with regex, that will show elements based on their data-user-name text match. For example, I want when the user types nd
in jQuery to catch both the Andi
and the Anderson
html elements,
when they type 'John' to catch both the John
and John Smith
elements,
and when they type 'John Smith' to show only the John Smith
element.
So far I've come up with this
$('#inputSearchFriends').on('input', function () {
const searchText = this.value.trim();
$('.friendListItem').filter(function() {
const re = new RegExp(searchText);
return this.attributes['data-user-name'].value.match(re);
}).show();
}
but it only returns the elements when the text is exactly entered. I also need the regex pattern to be case-insensitive, so if I type 'john' it will still match 'John'. How can I do it?