0

From this famous high-voted question I've find an effective way to check if a string contains another string or not with String.indexOf.

var abcde = "abcdefg";
var abc = "abc";
alert(abc.indexOf(abcde) != -1);//return true

But when I try to do like this:

var url = "https://stackoverflow.com/questions/1789945/method-like-string-contains-in-javascript";
var s = "stackoverflow";
alert(s.indexOf(url) != -1); //**return false,but I think it 'should' return true!**

I'm curious that why a more complex which contains symbol or slash / seems to be failed. Or did I miss something?

Community
  • 1
  • 1
Sam Su
  • 6,532
  • 8
  • 39
  • 80

1 Answers1

5

The string you search is the parameter, not the receiver.

Change

alert(s.indexOf(url) != -1); 

to

alert(url.indexOf(s) != -1); 

(and you should also use console.log instead of alert, for your own comfort)

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758