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

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

    An easy way to do it to use Regex match() method :-

    For Example

    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');
    }
    

    Check the fiddle

    NOTE: For adding case sensitiveness update the regex with /(^|\W)stack($|\W)/i

    Thanks

提交回复
热议问题