Escape Special Characters using jQuery

jQuery

jQuery is a javascript library that is simple to use. It’s easy enough to do very advanced things. Anyone who has used jQuery knows that you can do quite a lot with selectors. One of the problems I run into often is using a selector for a DOM element that contains special characters. jQuery requires many characters to be escaped in the selector in order to function properly. The problem here is that jQuery doesn’t offer a function that will escape your selector value for you. I’ve created such a function here:

// Escapes special characters and returns a valid jQuery selector
function jqSelector(str) {
    return str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\$1');
}

 

The HTML

If you want to use the jqSelector function, you can do so like this:

<div id="id.with,special#characters" class="testElem[1]"></div>

 

The javascript

// ID selector
$('#'+jqSelector('id.with,special#characters')).text('My Selected Element');

// Class selector
$('.'+jqSelector('testElem[1]')).text('My Selected Element');

This function will escape all of the special characters needed to form a proper jQuery selector.

Enjoy!

Leave a Reply

avatar
  Subscribe  
Notify of