首页 > 解决方案 > 匹配 JQuery 中的确切字符串

问题描述

例如,我有以下文本:

我想用字符串 Cap 过滤结果。我现在拥有的是检查字符串是否包含 asubstring但我想匹配实际单词。这就是我现在所拥有的

$('#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 );
    });
    ...
});

标签: jquery

解决方案


您可以创建一个自定义伪选择器,如下所示:hasword或使用 filter(function)

在每种情况下,按空格分割文本并查看结果数组是否包含所需的单词

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>


推荐阅读