JavaScript/jQuery - How to check if a string contain specific words

后端 未结 9 1850
北荒
北荒 2020-12-03 10:14
$a = \'how are you\';
if (strpos($a,\'are\') !== false) {
    echo \'true\';
}

In PHP, we can use the code above to check if a string contain speci

9条回答
  •  温柔的废话
    2020-12-03 10:49

    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;
    

    Update in ECMAScript2016:

    var a = 'how are you';
    return a.includes('are');  //true
    

提交回复
热议问题