Escape jQuery selectors
I've started to play with jQuery and needed an easy way to escape my selectors in situations when they're out of my control. A function like this will get the job done.
function escapeExpression(str) {
return str.replace(/([#;&,\.\+\*\~':"\!\^$\[\]\(\)=>\|])/g, "\\$1");
}
Reader comments
Post your own comment
Pages linking to this entry
Pingback is enabled on all archived entries. Read more about pingback in the Pingback 1.0 Specification.
No pingbacks.

Mark
I've been looking for this, thank you! Everyone was suggesting using consecutive replace() on the same string and I just didn't like the idea.
Filipus Klutiero
I'm adopting this after adding the backslash to metacharacters. Note that I'm wondering why the slash isn't escaped even if it's described as a meta-character on http://api.jquery.com/category/selectors/
It's not clear why it's a metacharacter though (as for &).
I would show the result, but your blog is stripping backslashes.