within a JavaScript string in a
I have an app that can generate all sorts of things into the JavaScript strings put on the page. I thought all the escaping were ok, but then I came across a weird problem that I couldn't really find a reason for:
Shouldn't this be legal in an html page:
<script type="text/javascript">
alert("hello </script>");
</script>
'Legal' meaning that it would produce an alert with hello </script>
.
Apparently both moz and chrome, on my box at least, cuts the scripting off after the </script>
part of the alert string, producing no alert and a messy output. Has anyone run into this, is this a browser bug?
The HTML parses it as:
<script type="text/javascript">
alert("hello
</script>
");
</script>
With the first occurrence of </script>
closing the open <script>
element. The common way of avoiding this issue is by including a \
before the /
character in the string:
<script type="text/javascript">
alert("hello <\/script>");
</script>
This works because the \
escape character will prevent the browser from recognizing <\/script>
as an end tag. Normally \
is used as an escape sequence in JavaScript strings, but as there's no \/
sequence, the escape character is ignored and the string evaluates as '</script'>
.
This issue can generally be avoided if you follow the good practice of keeping all of your javascript in external .js
files. That said, it's common to see this sort of escaping used for local script fallbacks for unresponsive CDNs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With