我可以在“indexOf”jQuery中搜索男/女关键字

时间:2014-02-12 10:24:24

标签: javascript jquery

我正在尝试使用indexOf()搜索这些关键字('男性','女性'),但它无效。 如果我发现'男性',它会搜索男性和女性的字符串。

这是正确的方法吗?

if ($(this).text().toUpperCase().indexOf(a.toUpperCase()) != -1) {
     $(this).show();
}

3 个答案:

答案 0 :(得分:1)

使用regex

尝试word boundaries
var regex = new RegExp('\b' + a + '\b', i)
if (regex.test($(this).text())) {
    $(this).show();
}

答案 1 :(得分:0)

您可以使用正则表达式仅查找单词(\b - 单词边界):

var str = 'There is one male and one female in this test';

if (str.match(/\bmale\b/i)) {
  console.log('Found male!');
} else {
  console.log('No male here!');
}


var str2 = 'There is one female and another female in this test';

if (str2.match(/\bmale\b/i)) {
  console.log('Found male!');
} else {
  console.log('No male here!');
}

答案 2 :(得分:0)

如果text="female"然后是,它会包含女性和男性这两个词,因此对男性的搜索不会毫不含糊。也许在整个弦乐中,有一些东西总是围绕着男性或女性的子串。例如text="sex=female“。如果是这种情况,那么您可以将额外的位添加到搜索模式中。

相关问题