Alex Rivera | Logout

Need to escape a special character in a jQuery selector string

Asked 2010-05-07T06:07:51.830
37

According to the selectors docs, you must escape [ with double backslash, etc \\[.

I have a selector that is created like so (assume val attribute is something[4][2] in this example).

var val = $(this).attr('val');           

$select.find('option[value=' +  val + ']').show();

Can I write a regex to escape the brackets for me?

Edit
Report

1 Answer

4

Check this out...

var val = $(this).attr('val').replace(/(\[|\])/g, '\\\\$1'); // something\\[4\\]\\[2\\]

of course, this only handles the brackets, not any other of the special characters. However, in my experience, the brackets are the only ones I use (because of PHP's handy way of handling input name attributes like these: something[])

answered 2010-05-07T06:08:30.097

Your Answer