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

后端 未结 9 1843
北荒
北荒 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

    0 讨论(0)
  • 2020-12-03 10:56

    You're looking for the indexOf function:

    if (str.indexOf("are") >= 0){//Do stuff}
    
    0 讨论(0)
  • 2020-12-03 11:01

    In javascript the includes() method can be used to determines whether a string contains particular word (or characters at specified position). Its case sensitive.

    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
    
    0 讨论(0)
提交回复
热议问题