-2

Was playing around with some code and just realized you can't write a script tag in a string without the browser trying to display:

<html>
 <head>
  <script>
    var code = "<script></script>";
  </script>
</head>

This prints to the screen. Weird - why this behavior?

cyberwombat
  • 38,105
  • 35
  • 175
  • 251

1 Answers1

1

This has nothing to do with JavaScript "string parsing". Rather it's about HTML parsing.

It is simply not valid for HTML for a <script> element to contain the sequence </script> (actually, any </ although browsers are lenient on that) in it's content - any such sequence will always be treated as the closing tag.

See Escaping </script> tag inside javascript for lots of the details.


A common solution is thus to separate the sequence using string concatenation

var code = "<script><"+"/script>";

Although it is also valid to use an escape ("<script><\/script>") or an escape sequence ("<script><\x2fscript>").

The CDATA approach should not be used with HTML, as it's only for XML.

Community
  • 1
  • 1
user2864740
  • 60,010
  • 15
  • 145
  • 220
  • Ah of course - I was not thinking this through! – cyberwombat Mar 24 '14 at 03:30
  • I expect the `"<\/"` version is better, as the script parser may turn `'<' + '/'` into `''` and see a closing tag. – RobG Mar 24 '14 at 03:34
  • @RobG No JavaScript parsing occurs before HTML script element is parsed - then the entire content is turned over to JS only *after* the HTML parser reads through the end of the element. I'm not sure why, and I can't argue why it'd be "better", but the string concatenation version seems to be the most prevalent in my experience. – user2864740 Mar 24 '14 at 05:41