How to check if a string contain specific words

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

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


If you are looking for exact words and don't want it to match things like "nightmare" (which is probably what you need), you can use a regex:

/bareb/gi

b = word boundary
g = global
i = case insensitive (if needed)

If you just want to find the characters "are", then use indexOf .

If you want to match arbitrary words, you have to programatically construct a RegExp (regular expression) object itself based on the word string and use test .


you can use indexOf for this

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

Edit : This is an old answer that keeps getting up votes every once in a while so I thought I should clarify that in the above code, the if clause is not required at all because the expression itself is a boolean. Here is a better version of it which you should use,

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

indexOf should not be used for this.

CORRECT 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

This will find a word, real word, not just if the letters of that word are somewhere in the string.

链接地址: http://www.djcxy.com/p/74092.html

上一篇: 正确的方法解析html到jQuery对象

下一篇: 如何检查一个字符串是否包含特定的单词