How to put “” in a javascript string?

What’s tripping you up is the </script>. The HTML parser doesn’t recognize Javascript strings or nested <script> tags, so it’s interpreting that as the closing tag for the initial <script>. That is, this part of the document is parsed as:

<script>                (open tag)
    alert("<script>     (text node - contents of the script)
</script>               (close tag)
");                     (text node - plain text)

The second </script> is ignored, as there’s no other <script> tag for it to close.

To work around this, break up </script so that the HTML parser doesn’t see it. For instance:

alert("<script><\/script>");

or:

alert("<script><" + "/script>");

or just put the code in an external Javascript file. This issue only arises for inline scripts.

Leave a Comment