JavaScript search() 未能找到“()"; [英] JavaScript search() fails to find "()"

查看:14
本文介绍了JavaScript search() 未能找到“()";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能看起来微不足道,但我是 JS 新手.我有这段代码:

This might seem trivial, but I'm new to JS. I have this piece of code:

alert(elementAction);    
var argumentsBegin = elementAction.search("(");
var argumentsEnd = elementAction.search(")");
alert(argumentsBegin);

elementAction 是一个字符串.代码的问题是它似乎没有找到括号.例如,第一个警报框显示:外(内)但是第二个根本没有出现.不过,如果我将 () 替换为 {},一切都会很酷.任何想法为什么这对我不起作用?

elementAction is a string. The problem with the code is it doesn't seem to find the parenthesis. The first alert box shows for example: outer(inner) But the second one doesn't appear at all. All is cool if I replace () with {}, though. Any thoughts why is this not working for me?

推荐答案

是:字符串的 search() 方法需要一个正则表达式作为参数,并将您传递的字符串视为正则表达式模式,其中括号具有特殊含义.使用 indexOf() 代替:

Yes: the search() method of strings expects a regular expression as the parameter and is treating the string you're passing as a regular expression pattern, in which parentheses have special meaning. Use indexOf() instead:

alert( elementAction.indexOf("(") ); 

这篇关于JavaScript search() 未能找到“()";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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