tags:

views:

135

answers:

3

I am encountering an issue where having a ending script tag inside a quoted string in JavaScript, and it is killing the script. I assume this is not expected behaviour. An example of this can be seen here: http://jsbin.com/oqepe/edit

My test case browser for the interested: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.4) Gecko/20091028 Ubuntu/9.10 (karmic) Firefox/3.5.4.

+2  A: 

You need to escape it, else it will be a part of the HTML.

var test = 'what the hell... \<\/script\> \<h1\>why?!?!?!\<\/h1\>';
LiraNuna
this is incorrect. this is a variable that is storing text. It is not inserted into the HTML. Using a tag other than script will not have the same results.
re5et
It's the way XML is being rendered. You can also wrap the script with <![CDATA[ and ]]>. It won't happen with other tags because the way the XML parser work (notably it treats script as text, and not as code).
LiraNuna
@LiraNuna Umm. No. An XML parser will treat `</script>` as "End of script" and `</notscript>` as a well-formness error. An HTML parser will treat `</anything>` as "end of script" and then if it is `</notscript>` as "Error with handling undefined by the specification". Only a tag soup parser (and possibly an HTML5 parser, I haven't read the draft closely enough to be sure) will treat `</notscript>` as part of the script.
David Dorward
Oh, and if you wrap with CDATA markers then that won't fix it for tag soup parsers.
David Dorward
+5  A: 

What happens?

The browser HTML parser will see the </script> within the string and it will interpret it as the end of the script element.

Look at the syntax coloring of this example:

<script>
var test = 'foo... </script> bar.....';
</script>

Note that the word bar is being treated as text content outside of the script element...

A commonly used technique is to use the concatenation operator:

var test = '...... </scr'+'ipt>......';
CMS
This does work, but I am surprised that I have to do it. Part of the problem is that I am scraping a page and storing the results in a JS variable. I have no real expectations of what Is coming back.
re5et
How are you storing it in a variable? Are you scraping server-side then generating `var x = <string>;`? If so, don't forget to JSON-encode it.
orip
Escape the /, don't split the string up into parts. IIRC it is still an error in HTML 4.x. It is certainly more fiddly to type, messier to read, more characters to deal with, and less efficient (since string concatenation isn't the cheapest of JS operations)
David Dorward
great i never knew it. :)
Rakesh Juyal
A: 

Another way to go arround this problem, and the most standart way would be doing something like this:

<script>
<![CDATA[
   var test = 'foo... </script> bar.....';
]]>
</script>
Hippo
This does not work.
Tom Ritter