2

I'm getting an "unterminated string literal" Javascript error with this code:

var test = '<script type="text/javascript">var s = document.createElement(\'SCRIPT\');</script></div>'; 

What am I doing wrong here? I'm escaping the single quotes, but it doesn't seem to make a difference. However, this code does work:

var test = 'var s = document.createElement(\'SCRIPT\');</div>';

What would the difference be? I must be missing something here.

Nicole
  • 31,900
  • 11
  • 72
  • 98
Jon Tackabury
  • 45,342
  • 49
  • 125
  • 164

3 Answers3

5

Break up that script tag the old-school way

var test = '<scr'+'ipt type="text/javascript">var s = document.createElement(\'SCRIPT\');</scr'+'ipt></div>';
Hemlock
  • 5,994
  • 1
  • 24
  • 36
0

It looks like a bug in whatever Javascript parser you're using.

Use double quotes as a workaround instead:

var test = '<script type="text/javascript">var s = document.createElement("SCRIPT");</script></div>';
Axel Fontaine
  • 32,887
  • 14
  • 101
  • 134
0

If your script is inline with the rest of the page, you may need to inform the parser that your Javascript code should not be parsed using CDATA.

<script type='text/javascript'>
<![CDATA[
// javascript code goes here, including '<' and '>' characters that could be interpreted as HTML tags
]]>
</script>
WorkerThread
  • 2,145
  • 2
  • 19
  • 22