Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

Hi
I want to check if string b is completely contain 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?
Thanks

share|improve this question
add comment (requires an account with 50 reputation)

marked as duplicate by Bergi, Andrew Whitaker, Luca Geretti, rationalboss, Joe Doyle Mar 23 at 18:24

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

6 Answers

up vote 4 down vote accepted

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.

share|improve this answer
add comment (requires an account with 50 reputation)

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

share|improve this answer
add comment (requires an account with 50 reputation)

.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)
share|improve this answer
add comment (requires an account with 50 reputation)

You need to test if the result is -1. -1 indicates no match, but evaluates to true in a boolean sense.

var a = "helloworld";
var b = "wold";
if(a.indexOf(b) > -1) { 
  document.write('yes'); 
} else { 
  document.write('no'); 
}
share|improve this answer
add comment (requires an account with 50 reputation)

That's because indexOf returns -1 if a value is not found:

if(a.indexOf(b) != -1) {
share|improve this answer
add comment (requires an account with 50 reputation)

you may want to use this

if(a.indexOf(b) != -1)
share|improve this answer
add comment (requires an account with 50 reputation)

Not the answer you're looking for? Browse other questions tagged or ask your own question.