mercredi 6 mai 2015

jQuery Attribute Equals Selector [name=”value”] issues passing a variable that ends with backslash

Humour me on this one.

In my code I am attempting to find all the divs that match a data-attribute value. Now this value is created by a user so the string could contain anything.

During my testing I ran into an error when the value contained a quote and ended with a backslash "\" (The javascript escape character).

Error: Syntax error, unrecognized expression: className[data-attributename="Mac"Mac\"]

Here is an example (please note in this example the double backslash escapes itself and the first backslash escapes the quote):

var value= "Mac\"Mac\\";
$('.className[data-attributename="'+value+'"]');

This error only occurs if the string contains a quote (") and has a backslash (\) at the end of the string. If there is a space after the backslash or if the backslash is in beginning or middle of the string there is no issue.

Is it possible to pass a variable that includes a quote or apostrophe ( " ' ) and ends with a backslash (\) into the jQuery Attribute Equals Selector?

One obvious solution would be just to prevent my users from using the backslash "\" character. If I do this is there any other characters that could be harmful using this jQuery selector?

Another solution would be:

var value= "Mac\"Mac\\";
$('.className').each(function(){
    if($(this).attr('data-attributename') === value){
      //perform action
    }
});

With this solution would it be less efficient because it would have to iterate through each element or does the Attribute Equals Selector essentially work the same way? If so, for safety should I always use this solution over the attribute equals selector?

Here is an example of the div I would be trying to select:

$('body').append("<div class='className' data-attributename='Mac\"Mac\\' ></div>")

Aucun commentaire :

Enregistrer un commentaire