0

I'm using the following selector with a string containing double quotes:

var something = 'This string contains "double" quotes';

$('*[my-data-attribute="' + something + '"]').click(function () {

});

This gives:

Uncaught Error: Syntax error, unrecognized expression

Which could be the best solution to solve it ?

andreasperelli
  • 1,034
  • 2
  • 11
  • 40
  • 1
    Have you tried using backticks(``) for the selector instead of the single quote? – AverageGod Jun 22 '21 at 08:47
  • 1
    Does this answer your question? [quotes in Jquery selectors](https://stackoverflow.com/questions/28817338/quotes-in-jquery-selectors) Use: `$('*[my-data-attribute="' + something.replace(/"/g, '\\"') + '"]')` – freedomn-m Jun 22 '21 at 08:48
  • use \ slash, the best or easy way to manage single and double quotes. – Zaid Bin Khalid Jun 22 '21 at 08:50

1 Answers1

0

You can't use one single quote and second double-quotes. You need to use the same quote like

var something = 'This string contains "double" quotes';

$('*[my-data-attribute="" + something + ""]').click(function () {

});
demo
  • 6,038
  • 19
  • 75
  • 149
Codexs
  • 19
  • 4
  • Hi, welcome to SO. You can create a snippet (edit and click `[<>]`, copy in your code and add jquery from the options on the left) to demonstrate your code working. In this case your code gives a similar error: `Syntax error, unrecognized expression: *[my-data-attribute="" + something + ""]` Using `""` doesn't "escape" the quote in javascript (it may in other languages (VB?)) – freedomn-m Jun 22 '21 at 08:58