javascript搜索字符串包含'+'

javascript search string contains ' + '

本文关键字:包含 搜索 字符串 javascript      更新时间:2023-09-26

我想把一个字符串搜索到另一个字符串中,但我遇到了一个问题。

这是我的代码:

reference = "project/+bug/1234";
str = "+bug/1234";
alert(reference.search(str));
//it should alert 8 (index of matched strings)

但它提醒-1:所以,在引用中找不到str。

我发现了问题所在,它似乎是str中的"+"字符,因为.search("string+str")似乎用regex"+"来评估搜索到的字符串

只需使用string.indexOf()。它采用一个文本字符串,而不是将字符串转换为RegExp对象(就像string.search()所做的那样):

> reference = "project/+bug/1234";
> str = "+bug/1234";
> console.log(reference.indexOf(str));
8

试试这个:

reference = "project/+bug/1234";
str = "+bug/1234";
alert(reference.indexOf("+bug/1234"));