It does not work as you think.
The first fragment of code does not work because the browser finds the </script>
piece in the string and thinks that it is the closing tag of the script element. It treats the rest of the script and the real </script>
closing tag as regular text and displays it in the page (except for the </script>
tag).
This means that only a fragment of your script is parsed, the parser finds a syntax error in it (the string is not closed) and the script does not run.
There is no way to fix this using JavaScript code. It is not a coding problem. It is an HTML problem (kind of) and its only solution is to write the HTML in a way that avoids the issue.
The HTML document contains a closing tag </script>
inside the body of a script
element. For normal HTML content (a paragraph, for example) the solution is straight forward: use <
and >
to encode <
and >
:
<p> This is a paragraph that contains a <p> closing tag</p>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…