最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript search() fails to find "()" - Stack Overflow

programmeradmin3浏览0评论

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 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?

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 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?

Share Improve this question asked Oct 20, 2010 at 11:40 Mateusz DymczykMateusz Dymczyk 15.1k10 gold badges62 silver badges94 bronze badges 1
  • What exactly are you trying to do? Try var arg = elementAction.match(/\\([^)]*\\)/); – Kobi Commented Oct 20, 2010 at 11:47
Add a comment  | 

2 Answers 2

Reset to default 13

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("(") ); 
elementAction.search("\\(");

search is regular expression, ( is keyword in regular expression. you have to escape ( to \(, \( in string is "\\("

发布评论

评论列表(0)

  1. 暂无评论