如何将"</ script>"放在javascript字符串中?

Vic*_*748 20 html javascript string

我一直在尝试javascript中的一些技巧并且出现了一个荒谬的问题:我不能<script>在javascript字符串中用作子字符串!这是一个例子:

<html>
    <head>
        <script>
            alert("<script></script>");
        </script>
    </head>
</html>
Run Code Online (Sandbox Code Playgroud)

它应该打印出来<script></script>,但相反,我得到这个:

");
Run Code Online (Sandbox Code Playgroud)

以HTML格式打印在页面上.

问题:如何在Javascript中使用字符串中的子字符串<script>后跟</script>任何原因?

这是它的JSFiddle :)

dus*_*uff 28

绊倒你的是什么</script>.HTML解析器无法识别Javascript字符串或嵌套<script>标记,因此它将其解释为初始化的结束标记<script>.也就是说,文档的这一部分被解析为:

<script>                (open tag)
    alert("<script>     (text node - contents of the script)
</script>               (close tag)
");                     (text node - plain text)
Run Code Online (Sandbox Code Playgroud)

第二个</script>被忽略,因为它没有其他<script>标签可以关闭.

要解决此问题,请分解</script以便HTML解析器不会看到它.例如:

alert("<script><\/script>");
Run Code Online (Sandbox Code Playgroud)

要么:

alert("<script><" + "/script>");
Run Code Online (Sandbox Code Playgroud)

或者只是将代码放在外部Javascript文件中.此问题仅出现在内联脚本中.