javascript搜索字符串包含'+' [英] javascript search string contains ' + '

查看:49
本文介绍了javascript搜索字符串包含'+'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i would to search a string into another string but i'm facing an issue.

这是我的代码:

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

但它警告 -1 :因此,没有找到 str 参考.

but it alert -1 : so, str wasn't found into reference.

我发现了问题所在,它似乎是+"字符到 str 中,因为 .search("string+str") 似乎使用正则表达式+"评估搜索字符串

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 " + "

推荐答案

只需使用 string.indexOf().它需要一个文字字符串而不是将字符串转换为 RegExp 对象(如 string.search() 确实):

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

这篇关于javascript搜索字符串包含'+'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆