32

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?

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Charles Yeung
  • 38,347
  • 30
  • 90
  • 130
  • related: [Method like String.contains() in JavaScript](http://stackoverflow.com/questions/1789945/method-like-string-contains-in-javascript) – Bergi Mar 23 '13 at 16:11

6 Answers6

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.

4

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

Ry-
  • 218,210
  • 55
  • 464
  • 476
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)
deceze
  • 510,633
  • 85
  • 743
  • 889
0

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

if(a.indexOf(b) != -1) {
onteria_
  • 68,181
  • 7
  • 71
  • 64
0

you may want to use this

if(a.indexOf(b) != -1)
rob waminal
  • 18,117
  • 17
  • 50
  • 64
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'); 
}
Kyle
  • 828
  • 8
  • 8