Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check a string that MUST contain another string [duplicate]

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?

like image 729
Charles Yeung Avatar asked Aug 31 '25 21:08

Charles Yeung


1 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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!