5

I have seen everyone doing it tho i dont' get why.

document.write('<script src="src"><\/script>');

I mean using the single ' you shouldn't need to esacape chars?

dynamic
  • 46,985
  • 55
  • 154
  • 231

3 Answers3

5
  1. Single and double quoted strings have the same escaping rules.
  2. It prevents </script> from being parsed as an closing tag.

"</script> and "<\/script>" are the same to JavaScript, but only the first one is interpreted by the HTML parser to contain a HTML closing tag.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
4

The HTML-parser will see the </script> in your string as a closing tag and close your initial <script>. It does not have the concept of strings.

So your piece of JavaScript will only be seen as document.write('<script src="src"> if you dont escape it and the rest, '); will be seen as a HTML text-node.

Also, note that you don't have to "escape" the </script> in a particular way. As long as you don't write it exactly like </script>, anything is ok. Some examples that all work:

document.write('<script src="src"><\/script>');
document.write('<script src="src"></scr' + 'ipt>');
document.write('<script src="src"></' + 'script>');
Jakob
  • 24,154
  • 8
  • 46
  • 57
3

</script> always ends a script block - no matter what (e.g. HTML comments or CDATA) you do. So it must never occur in a script block unless you actually want to end the block and the easiest way to do so is escaping forward slashes (the escaping doesn't do anything; in JavaScript unknown escape sequences just "lose" their backslash).

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636