Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript search() fails to find "()"

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?

like image 674
Mateusz Dymczyk Avatar asked Oct 20 '10 11:10

Mateusz Dymczyk


2 Answers

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("(") ); 
like image 150
Tim Down Avatar answered Sep 23 '22 15:09

Tim Down


elementAction.search("\\(");

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

like image 23
guilin 桂林 Avatar answered Sep 23 '22 15:09

guilin 桂林