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?

3
  • Possible duplicate of stackoverflow.com/questions/236073/… Commented Mar 29, 2011 at 17:22
  • Only PHP has this stupid "no escaping in single quote strings" rule Commented Mar 29, 2011 at 19:57
  • @thief: that rule of PHP is perfectly fine Commented Mar 29, 2011 at 20:02

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

4 Comments

I don't get it. Considering javascript escapes in single quote too, aren't </script> and <\/script> the same value? Shouldn't they produce the same "error"
Yes, but it is not only longer (3 chars instead of 1 char) but also looks uglier (IMO).
@yes, yes, and I've seen that style before.
@yes, please don't edit your comment to say something entirely different. Just post a new one.
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>');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.