0

This works :

var str ='<input id="a_49519498" type="radio" name="answers[10903336]" value="49519498" />cat,dog       ';

if(str.search('cat,dog')!=-1)
    {
    alert("found ");
    }

While this does not :

var str ='<input id="a_49519498" type="radio" name="answers[10903336]" value="49519498" />Rock (Foreigner, Nickelback, etc...)       ';

if(str.search('Rock (Foreigner, Nickelback, etc...)')!=-1)
    {
    alert("found ");
    }

​I am guessing that this has something to do with the brackets that are present in

(Foreigner, Nickelback, etc...)

Why is JavaScript unable to find this string ? How can I make it work?

0

3 Answers 3

3

It seems .search [MDN] converts the argument into a regular expression:

If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).

The parenthesis are then interpreted as capture group and not taken literally.

It seems you don't want to use regular expressions, so you could just use .indexOf [MDN] instead:

if(str.indexOf('Rock (Foreigner, Nickelback, etc...)') != -1)
Sign up to request clarification or add additional context in comments.

Comments

2

You need to do add escapes before your paranthesis, normally it would be 1 paranthesis, but in this case the () create a group so we need to use \\ two.

\\(
\\)

str.search('Rock \\(Foreigner, Nickelback, etc...\\)')

jsFiddle Demo

2 Comments

i can't add those i am dynamically extracting the data from a webpage
You need to simply look through look through the string before you do your search for ( or ) and replace them with \\( and \\) before you do your .search()
1

String.search searches for a regular expression, not a string literal (see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/search). Just escape your parentheses:

str.search('Rock \\(Foreigner, Nickelback, etc...\\)'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.