Norseback
Norseback

Reputation: 315

Match exact string in JQuery

For example, I have the following text:

I want to filter results with the string Cap. What I have right now is checking if the string contains a substring but I want to match the actual word. This is what I have right now

$('#filter').click(function() {
    ...
    // Filters items based on the search criterias.
    $('figure.col-sm-3')
    .has('tr:last-child>td:last-child:contains(' + month + ')')
    .has('tr:last-child>td:last-child:contains(' + year + ')')
    .has('h6:contains(' + brand + ')')
    .has('h6:contains(' + type + ')')
    .has("tr.price td:nth-child(even)")
    .each(function(index, self) {
        var price = $(self).find("tr.price td:nth-child(even)").eq(0).text();
        arr.push(price);
        totalPrice += parseFloat( price );
    });
    ...
});

Upvotes: 0

Views: 63

Answers (1)

charlietfl
charlietfl

Reputation: 171700

You could create a custom pseudo selector such as the following :hasword or use filter(function)

In each case split the text by space and see if the resultant array includes the desired word

const word = 'Cap';

$.expr[':'].hasword = function(elem, i, match) {
   const words = $(elem).text().trim().split(' ')
   return words.includes(match[3]);   
}

$('.foo:hasword(' + word + ')').css('color','red');

$('.foo').filter(function(i,elem){
    const words = $(elem).text().trim().split(' ')
    return words.includes( word)
}).css('background', 'yellow')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foo">Green Baseball Cap</div>
<div class="foo">Cape Canaveral</div>
<div class="foo">Cap</div>
<div class="foo">Cape</div>

Upvotes: 1

Related Questions