javascript script script gotcha script
Today’s javascript lesson is about the wonderfully helpful <script> tag. Unfortunately, it is not all roses when you use <script>. For example, the following will produce a syntax error in most browsers:
<script type="text/javascript">
<!--
document.write("Here is some text.<script type=\"text/javascript\"><!--nalert(\"done!\");n--></script>");
-->
</script>
Usually, the error will say something about an unterminated string. The cause isn’t obvious, especially if you are dealing with a much, much longer string. Here is a smaller example which will cause the same error:
<script type="text/javascript">
<!--
var foo = "<script></script>";
-->
</script>
Maybe you’re like me. Maybe you’re staring at this late at night as the caffeine is wearing off. Maybe you won’t see the problem until it’s made even simpler:
<script type="text/javascript">
<!--
var bar = "</script>";
-->
</script>
At this point, I had an “A-Ha!” moment (I even believed that this javascript was singing “Take On Me”; it was quite late). On a whim, I tried:
<script type="text/javascript">
<!--
var bar = "</" + "script>";
-->
</script>
It worked! It worked! Here’s the rub: Browsers aren’t paying attention to the contents of your <script> tag when they’re searching for the matching end </script>. They’ll grab the first </script> they see, even if it’s embedded in a javascript string. As a result, the script tag is closed prematurely, and terminates your string at the point of the </script>. The syntax error is due to the truncated string.
You can workaround this problem by splitting your strings whenever you see a </script> tag. Something like the following will work (using ERB syntax):
<script type="text/javascript">
<!--
<% content.gsub! /</script>/, '</"' + '"script>' -%>
document.write("<= content %>");
</script>
We are inserting close-quotes for the first part of the string, open-quotes for the second part of the string, and a plus sign to join them. Make sure your replacement quotes match the quoting where the string is embedded in your JS.
No comments yet. Be the first.
Leave a reply

