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

后端 未结 9 1874
北荒
北荒 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:38

    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:

    /\bare\b/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.

提交回复
热议问题