3 ms·
If you write HTML, only </script> will end the Javascript parsing and make the parser go back to parsing HTML. This is the only thing you need to escape if it a
by jraph 5y ago
If you write HTML, only </script> will end the Javascript parsing and make the parser go back to parsing HTML. This is the only thing you need to escape if it appears in the Javascript code (by using something like '<' + '/script>' for instance). You CANNOT escape special HTML characters (&, <, >) because the parser is interpreting Javascript code, not HTML (but still looking for </script>).
If you write XHTML, special HTML (XML) characters in <script> MUST be escaped. You can avoid having to escape manually by putting your Javascript between <![CDATA[ and ]]>. That's because the XML parser does not have special handling of script tags, contrary to HTML, and will not forgive any unescaped special character. It will parse them as tags and entities if they happen to be syntactically valid XML tags or entities.
If you write polyglot HTML / XHTML, CDATA sections will not handled as such by the HTML parser and will break your javascript because <![CDATA[ will be parsed as Javascript, and that does not work. But you can put them in javascript comments, like this:
<script>
// <![CDATA[
let your_code = "be here";
// ]]>
</script>
(you will also need to "escape" both "</script>" and "]]>" if they ever appear in the Javascript code).
In XHTML mode, the Javascript will look like this after parsing:
//
let your_code = "be here";
//
(because CDATA are interpreted in XML, and "replaced" by their content)
In HTML mode:
// <![CDATA[
let your_code = "be here";
// ]]>
(because CDATA sections are not recognized, so they will be handled as normal commented javascript code)