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
  • 32,841
  • 11
  • 75
  • 101
Jon Tackabury
  • 47,710
  • 52
  • 130
  • 168

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
  • 6,130
  • 1
  • 27
  • 37
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
  • 34,542
  • 16
  • 106
  • 137
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,195
  • 2
  • 19
  • 23