0

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>")
Mac
  • 1,025
  • 3
  • 12
  • 22

2 Answers2

1

You will have to use the second solution to get jQuery working. Similar questions have been asked an this is an answer to one of them. jQuery selector value escaping

$("#SomeDropdown >option[value='a\\'b]<p>']")

But this doesn't work in jQuery because its selector parser is not completely standards-compliant. It uses this regex to parse the value part of an [attr=value] condition:

(['"]*)(.*?)\3|)\s*\]

\3 being the group containing the opening quotes, which weirdly are allowed to be multiple opening quotes, or no opening quotes at all. The .*? then can parse any character, including quotes until it hits the first ‘]’ character, ending the match. There is no provision for backslash-escaping CSS special characters, so you can't match an arbitrary string value in jQuery.

FastFarm
  • 409
  • 1
  • 6
  • 21
0

You can use escape() function to escape the special character like

value = escape('Max\\'); //it will return Max%5C
tarikul05
  • 1,843
  • 1
  • 16
  • 24
  • This does not work because the selector would literally look for a value of "Max%5C" when the attribute value is "Max\" – Mac May 01 '15 at 19:58