Search code examples
javascriptescapingquotes

Havoc while escaping quotes in Javascript


I am trying to build a custom HTML/Javascript command using the following Javascript (for now, "dialogText" contains the name of a vegetable, but it may later contain HTML tags too):

str = str + "<span onClick=showDialog('"+dialogText+"')>";

When dialogText is only one word long (i.e. "Basil"), this works correctly, giving the following result:

<span onclick="showDialog('Basil')">

But when dialogText includes more than one word (i.e. "Beet root"), this fails. The result is syntactically invalid and generates a Javascript error:

<span onclick="showDialog('Beet" root')="">

Why does this happen (where did the equals sign come from?)?

And how can I change the code so that it works?


Solution

  • You aren't looking at the HTML you are generating, you are converting that HTML to a DOM and then serializing it back to HTML.

    Since you have a " as data in the attribute value, but haven't represented it as a character reference (&quot;), and the value is limited with " - the " ends the attribute.

    You then start a new attribute.

    Since the next attribute doesn't have a value, it gets assigned an empty string when the browser attempts to error correct.


    In general, avoid mashing strings together to generate HTML for conversion to a DOM. Use DOM methods directly instead.

    var span = document.createElement('span');
    span.addEventListener('click', function (event) {
        showDialog(dialogText);
    });