jQuery selector escaping

jQuery selectors are powerful and simple to use, until you have attribute
values (including ids and classes) that have funny characters. I wrote a plugin
adds a simple function $.escape that will escape any special characters.
For example if I have a string s that contains an id but I’m not sure that
all of the characters are safe I can use $('#'+$.escape(s)) to find the
element with that id. If I want to find all of the links to
http://ianloic.com/ I can do $('a[href='+$.escape('http://ianloic.com/')+']')

The first release is here. I don’t know that there will be any more releases – this is a pretty damn simple plugin.

7 replies on “jQuery selector escaping”

  1. Hi there,

    Thanks for publishing your plugin.
    Just sharing a modified version that I made to avoid using recursive functions.

    The comparison method seems a bit lengthy but I think it’s faster than doing regular expressions continuously.

    (function($) {
    if ($) {
    var escape_re = /[#;&,\.\+\*~’:”!\^\$\[\]\(\)=>|\/\\]/,
    escapeCharacters = {
    ‘#’: 1,
    ‘;’: 1,
    ‘&’: 1,
    ‘,’: 1,
    ‘.’: 1,
    ‘+’: 1,
    ‘*’: 1,
    ‘~’: 1,
    ‘\”: 1,
    ‘:’: 1,
    ‘”‘: 1,
    ‘!’: 1,
    ‘^’: 1,
    ‘$’: 1,
    ‘[‘: 1,
    ‘]’: 1,
    ‘(‘: 1,
    ‘)’: 1,
    ‘=’: 1,
    ‘>’: 1,
    ‘|’: 1,
    ‘/’: 1,
    ‘\\’: 1
    $.escape = function(s){
    var ret = ”, offset;
    if (s && ((offset = s.search(escape_re)) !== -1)) { // look for an occurence of a special character
    ret = s.substr(0, offset) + ‘\\’ + s[offset];
    for(var i=offset + 1, len=s.length, ch; i < len; i++){ // assume that another special character may occur so we just loop through the rest of the string
    ch = s[i];
    ret += (escapeCharacters[ch]? '\\': '') + ch;
    return ret;



  2. Hello Ian, I’ve just found this page. I have a problem using jquery with special characters in spanish (á, é, í, ó, ú, ñ, etc.)… the problem is explained in detail in:


    Maybe the solution is a piece of cake for you, using some function available in your jquery-plugin; I’ve searched for days without any answer.

    Thanks in advance for any hints.
    Ignacio Gallego Sagastume (La Plata, Argentina)

  3. Thanks Ian.

    One comment I have is that using the regex /\W/ will allow you to easily match against the entire set of special characters and will be much more generic than maintaining a long list of the possibilities.

    1. @Michael H,

      Using \W (which according to the ECMAScript spec is defined to be basically [a-ZA-Z0-9_]) would work but stylistically I prefer calling out explicitly which characters we need to escape. That way we’ll escape potentially less characters.

  4. Thanks for the regex.

    function jqescape(str) { return str.replace(/[#;&,\.\+\*~':"!\^\$\[\]\(\)=>|\/\\]/g, '\\$&'); }

Comments are closed.