0

I have a page with the following code:

<script>
window.str = '<script></script>';
</script>

This results in an error:

Uncaught SyntaxError: Unexpected token ILLEGAL

What's going on? Entering the same code into the console runs without issue. Here is a jsbin demonstrating the issue

8
  • And some of those: [javascript] "</script>" Commented Apr 13, 2014 at 3:06
  • The </script> tag inside the string closes the first <script> tag, leaving you with invalid JavaScript. HTML doesn't know about JavaScript, it only sees the closing tag. It works in the console because the code is not in a HTML context. Commented Apr 13, 2014 at 3:09
  • Oh good find @FelixKling that was it. Wow, I don't think I've learned something new about javascript in months if not years. Commented Apr 13, 2014 at 3:10
  • :) It's more an HTML issue than a JS issue, I'd say, but it's nice to learn something new :) Commented Apr 13, 2014 at 3:11
  • 1
    Yeah, I'll leave it up and vote to close - I asked in a different way than the dupe OP. Commented Apr 13, 2014 at 3:13

2 Answers 2

3

the error went away when I escaped the / with a \.

http://jsbin.com/xugabolu/1/edit

Sign up to request clarification or add additional context in comments.

Comments

1

The hackish work-around for this is something like:

<script>
window.str = '<scr' + 'ipt></scri' + 'pt>';
</script>

In this way, you wind up with the string you want without confusing the parser.

Or, insert it as a DOM element if that is the ultimate goal.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.