Search code examples
javascriptescapingquotesjinja2

Why does an escaped single qoute ' end javascript string?


I'm using Jinja2 to insert a string inside a javascript function like so:

<button type="button" onclick="someFunction('{{ aStringWithSignleQuote }}');">

I have the autoescaping function of jinja turned on, such that a single quote is rendered as

&#39;

and if I look at the source code of the page, then this works (I see the escaped charakter), but when I click the button, there is an error, because javascript thinks, the string ends at the escaped single quote.

Someone has a guess whats happening here?


Solution

  • Since it is in an HTML attribute value, it is processed by the HTML parser before being processed by the JavaScript parser.

    If you want to escape it for JavaScript, you need to escape it for JavaScript (with \).