javascript search string contains ' + '

余生长醉 提交于 2021-02-08 06:16:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!