How to put "</script>" in a javascript string?

I've been trying some tricks in javascript and came to a ridiculous problem: I can't use <script> as a substring in a javascript string! Here is an example:

<html>
    <head>
        <script>
            alert("<script></script>");
        </script>
    </head>
</html>

It supposed to print out <script></script>, but instead, I get this:

");

Printed out on the page, as HTML.

Question: How can I use <script> followed by </script> substrings in Javascript, and why is it acting that way?

Here is JSFiddle of it.


Solution 1:

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.

Solution 2:

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.