0

Why this seemingly simple string variable is syntactically wrong?

var str = "<script>functionName()</script>";

I am getting the following error

Uncaught SyntaxError: Unexpected token ILLEGAL

here is the fiddle

gurvinder372
  • 66,980
  • 10
  • 72
  • 94

2 Answers2

2

Open the console and try putting the string

var str = "<script>functionName()</script>";

There are no syntax errors and everything works fine.

When you are embedding the code in a script tag, like so

<script>
// code here
</script>

In JSFiddle, if you check the error you will see something like

<script type='text/javascript'>//<![CDATA[
window.onload=function(){
var str = "<script>functionName()</script>";
}//]]> 

</script>

The Browser does not allow </ characters in a string when you are embedding it in a <script> tag.

So, you'll need to escape it with a \

GokulSrinivas
  • 383
  • 2
  • 10
1

This should work. Added a backslash "</script>".

<script>
    var str = "<script>functionName()<\/script>";
</script>
Keyur Sakaria
  • 680
  • 1
  • 5
  • 12