Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
421 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...