Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

javascript - Need to escape a special character in a jQuery selector string

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...