JavaScript / jQuery – 如何检查字符串是否包含特定单词

$a = 'how are you'; if (strpos($a,'are') !== false) { echo 'true'; } 

在PHP中,我们可以使用上面的代码来检查字符串是否包含特定的单词,但是如何在JavaScript / jQuery中执行相同的function呢?

如果你正在寻找确切的单词,并且不希望它匹配“梦魇”(这可能是你需要的)之类的东西,你可以使用正则表达式:

 /\bare\b/gi \b = word boundary g = global i = case insensitive (if needed) 

如果你只想找到字符“are”,那么使用indexOf

如果要匹配任意单词,则必须以字符串和使用testforms以编程方式构造一个RegExp(正则表达式)对象。

你可以使用indexOf

 var a = 'how are you'; if (a.indexOf('are') > -1) { return true; } else { return false; } 

编辑 :这是一个古老的答案,每隔一段时间不断获得投票,所以我认为我应该澄清,在上面的代码中, if子句根本不需要,因为表达式本身是一个布尔值。 这是你应该使用的更好的版本,

 var a = 'how are you'; return a.indexOf('are') > -1; 

indexOf不应该用于此。

正确的function:

 function wordInString(s, word){ return new RegExp( '\\b' + word + '\\b', 'i').test(s); } wordInString('did you, or did you not, get why?', 'you') // true 

这将找到一个单词,真正的单词,而不仅仅是该单词的字母在字符串中的某个位置。

您正在寻找indexOf函数:

 if (str.indexOf("are") >= 0){//Do stuff} 

这将

 /\bword\b/.test("Thisword is not valid"); 

返回false ,当这个

 /\bword\b/.test("This word is valid"); 

将返回true

你可能想在JS中使用include方法。

 var sentence = "This is my line"; console.log(sentence.includes("my")); //returns true if substring is present. 

PS:包含区分大小写。

 var str1 = "STACKOVERFLOW"; var str2 = "OVER"; if(str1.indexOf(str2) != -1){ console.log(str2 + " found"); } 

一个简单的方法来使用Regex match()方法: –

例如

 var str ="Hi, Its stacks over flow and stackoverflow Rocks." // It will check word from beginning to the end of the string if(str.match(/(^|\W)stack($|\W)/)) { alert('Word Match'); }else { alert('Word not found'); } 

检查小提琴

注意:要添加区分大小写,请使用/(^|\W)stack($|\W)/i更新正则表达式

谢谢