How to put "</script>" 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.


it is because of the \ I believe. i have no concrete explanation since I am a newbie to Javascript but this code should work:

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

came up with it using Java knowledge.. Haha since the \ is an escape key in many languages.