"If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: \\."
Unfortunately, jQuery doesn't offer any function to escape these characters within a string, so that you don't have to care about what characters you must not use when defining attributes of your markup.
So I've spent almost one hour playing (or better fighting) with regular expressions in order to create a general function to escape strings to use in jQuery selectors. So if you're an absolutely RegEx guru or just have the time to figure out the right regular expression to use for this purpose, then you're probably not so interested in the following function. Otherwise, you should really try it out! ;)
function jQuerySelectorEscape(expression) {
return expression.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~]/g, '\\$&');
}
The function inserts a backslash before all meta-characters for jQuery selectors within a string.
Here's an example:
<div id="my#div$has[some]strange*characters">My DIV</div>
<br/>
<script type="text/javascript">
var selector = '#' + jQuerySelectorEscape('my#div$has[some]strange*characters');
document.write('selector = ' + selector);
document.write('<br/><br/>');
document.write('DIV content = ' + jQuery(selector).html());
</script>Output:My DIV selector = #my\#div\$has\[some\]strange\*characters DIV content = My DIV
I hope you can avoid some headaches with this function. If there's any question or problem with it, leave a comment below and I'll try to help you out.
Using this on a jsp file doesn't seem to work as here, only in js file it seems. In the jsp file i had to put two more "\" in the replace method so it would stay like this:
ReplyDeletereturn expression.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~]/g, '\\\\$&');
It depends on your JSP. This code is meant to be used within the Javascript context, i. e. like you said in a js file, or inside a <script> block of a HTML page for example. Actually it also should work inside a JSP, as long as you're not inside the Java context (i. e. inside <% %>), otherwise you would have to escape again all meta characters used in Java.
DeleteYes i mean placing it in the jsp file inside the script block tag as if it was an html page.
DeleteVery handy. You should also add \s to your regex.
ReplyDeleteThanks, I usually don't use whitespaces inside HTML attributes, so I've never needed \s. And since whitespaces are not in the documentation (see quote above), I'm not sure what jQuery would do with it.
DeleteThanks for this, was useful for me :)
ReplyDelete