dynamic
dynamic

Reputation: 48131

why escaping / in javascript '<\/script>'?

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?

Upvotes: 5

Views: 1513

Answers (3)

Matthew Flaschen
Matthew Flaschen

Reputation: 284927

  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.

Upvotes: 5

Jakob
Jakob

Reputation: 24370

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>');

Upvotes: 4

ThiefMaster
ThiefMaster

Reputation: 318558

</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).

Upvotes: 4

Related Questions