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?
Read the documentation: MDC String.indexOf 🙂
indexOfreturns the index the match was found. This may be 0 (which means “found at the beginning of string”) and 0 is a falsy value.indexOfwill 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 >= 0orindex > -1orindex != -1; String not found:index < 0orindex == -1.Happy coding.