Thursday, 19 July 2018

javascript - Check a string that MUST contain another string




I want to check if string b is completely contained in string a.
I tried:




var a = "helloworld";
var b = "wold";
if(a.indexOf(b)) {
document.write('yes');
} else {
document.write('no');
}


The output is yes, it is not my expected output, because string b(wold) is not completely contained in string a(helloworld) --- wold v.s. world




Any suggestion to check the string?


Answer



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.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...