Need to escape a special character in a jQuery selector string
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.
CSS character escape sequences (as used in selectors) are tricky. They’re so tricky I even made a web app that can tell you how to escape any character in CSS.
It’s much simpler and more efficient to simply select all option
elements and then filter
them based on their value
attribute value:
var value = this.value;
$select.find('option').filter(function() {
return this.value == value;
}).show();
That way, no special escaping is needed at all.