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

Cha*_*ung 22 javascript jquery

$a = 'how are you';
if (strpos($a,'are') !== false) {
    echo 'true';
}
Run Code Online (Sandbox Code Playgroud)

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

nai*_*vin 56

你可以使用indexOf

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

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

var a = 'how are you';
return a.indexOf('are') > -1;
Run Code Online (Sandbox Code Playgroud)

ECMAScript2016中的更新:

var a = 'how are you';
return a.includes('are');  //true
Run Code Online (Sandbox Code Playgroud)

  • 非常糟糕的答案.这会失败:'你怎么样' (4认同)

vsy*_*ync 26

indexOf 不应该用于此.

正确的功能:

function wordInString(s, word){
  return new RegExp( '\\b' + word + '\\b', 'i').test(s);
}

wordInString('did you, or did you not, get why?', 'you')  // true
Run Code Online (Sandbox Code Playgroud)

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


Ste*_*ung 24

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

/\bare\b/gi

\b = word boundary
g = global
i = case insensitive (if needed)
Run Code Online (Sandbox Code Playgroud)

如果你只想找到"是"字符,那就用吧indexOf.

如果要匹配任意单词,则必须根据单词string和use以编程方式构造一个RegExp(正则表达式)对象test.


evb*_*ley 6

您正在寻找indexOf函数:

if (str.indexOf("are") >= 0){//Do stuff}
Run Code Online (Sandbox Code Playgroud)


Zen*_*eni 6

在 JavaScript 中,includes() 方法可用于确定字符串是否包含特定单词(或指定位置的字符)。它区分大小写。

var str = "Hello there."; 

var check1 = str.includes("there"); //true
var check2 = str.includes("There"); //false, the method is case sensitive
var check3 = str.includes("her");   //true
var check4 = str.includes("o",4);   //true, o is at position 4 (start at 0)
var check5 = str.includes("o",6);   //false o is not at position 6
Run Code Online (Sandbox Code Playgroud)


Nee*_*rma 5

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

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

PS:包含区分大小写。


小智 5

一种简单的方法是使用 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');
}
Run Code Online (Sandbox Code Playgroud)

检查小提琴

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

谢谢