35

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?

1

6 Answers 6

9

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

3

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

Comments

0

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

if(a.indexOf(b) != -1) {

Comments

0

you may want to use this

if(a.indexOf(b) != -1)

Comments

0

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'); 
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.