Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
82
rated 0 times [  87] [ 5]  / answers: 1 / hits: 67371  / 14 Years ago, fri, may 7, 2010, 12:00:00

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?


More From » jquery

 Answers
2

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



var val = $(this).attr('val').replace(/[!#$%&'()*+,./:;<=>?@[\]^`{|}~]/g, \\$&)


This works by escaping all CSS meta-characters listed on the Selectors page of the jQuery documentation with two backslashes.



Keep in mind that in your situation, there is no need to do something tricky like this. You can use the filter function to select all option elements with a given value without having to escape the value, as described in Mathias Bynens's answer.


[#96855] Tuesday, May 4, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
julian

Total Points: 159
Total Questions: 105
Total Answers: 94

Location: Chad
Member since Mon, Dec 5, 2022
1 Year ago
;