Samuel Sjöberg's weblog

Skip to navigation

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

  1. 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.

    1st October 2009, 18:57 CET. 
  2. 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.

    12th February 2010, 07:05 CET. 

Pages linking to this entry

Pingback is enabled on all archived entries. Read more about pingback in the Pingback 1.0 Specification.

About this post

Created 3rd September 2009 14:57 CET. Filed under jQuery, Javascript and DOM.

2 Comments
0 Pingbacks