2014-02-12 14 views
0

我試圖使用indexOf搜索這些關鍵字('男性','女性'),但它在這裏不起作用。 如果我發現「男性」,它搜索字符串男性和女性。我可以在「indexOf」中搜索男性和女性關鍵字jquery

請告訴我。這是一個正確的方法嗎?

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

請注意,'女'確實包含'男',這可能會解釋你的問題 –

+0

我有兩個下拉男和女,如果我選擇男性下拉,它顯示男性和女性.. –

回答

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!'); 
} 
1

嘗試regexword boundaries

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

如果text="female"然後是它contatins的話女性和男性,所以尋找男性不會是明確的。也許在整個字符串中總有一些東西圍繞着字符串男性或女性。例如「。如果是這樣的話,那麼你可以添加額外的位到你的搜索模式。

相關問題