views:

82

answers:

2

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?

+1  A: 

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[])

alex
+1  A: 

If you want something that works with any sort of value, try this:

var val = $(this).attr('val').replace(/[#;&,.+*~':"!^$[\]()=>|\/]/g, "\\\\$&");
mikez302