问题
i would to search a string into another string but i'm facing an issue.
There is my code :
reference = "project/+bug/1234";
str = "+bug/1234";
alert(reference.search(str));
//it should alert 8 (index of matched strings)
but it alert -1 : so, str wasn't found into reference.
I've found what's the problem is, and it seems to be the " + " character into str, because .search("string+str") seems to evaluate searched string with the regex " + "
回答1:
Just use string.indexOf(). It takes a literal string instead of converting the string to a RegExp object (like string.search() does):
> reference = "project/+bug/1234";
> str = "+bug/1234";
> console.log(reference.indexOf(str));
8
回答2:
Try this:
reference = "project/+bug/1234";
str = "+bug/1234";
alert(reference.indexOf("+bug/1234"));
来源:https://stackoverflow.com/questions/17363955/javascript-search-string-contains