Thursday, July 19, 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

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...