Check a string that MUST contain another string

This question already has an answer here:

  • How to check whether a string contains a substring in JavaScript? 49 answers

  • Read the documentation: MDC String.indexOf :)

    indexOf returns the index the match was found. This may be 0 (which means "found at the beginning of string") and 0 is a falsy value.

    indexOf will return -1 if the needle was not found (and -1 is a truthy value). Thus the logic on the test needs to be adjusted to work using these return codes. String found (at beginning or elsewhere): index >= 0 or index > -1 or index != -1 ; String not found: index < 0 or index == -1 .

    Happy coding.


    You need to use if(a.indexOf(b) > -1) instead. indexOf returns -1 when it can't find a string.


    .indexOf returns -1 if no match was found, which is a truthy value. You'll need to check more explicitly:

    if (a.indexOf(b) != -1)
    
    链接地址: http://www.djcxy.com/p/2054.html

    上一篇: javascript if语句如果url包含子字符串

    下一篇: 检查一个必须包含另一个字符串的字符串