Why can't js understand the string '</script>'?

I have a simple javascript (jsFiddle) :

alert('</script>'); 

The browser does not understand this. This is the console output:

 Uncaught SyntaxError: Unexpected token ILLEGAL 

But this script works (jsFiddle) :

 alert('</scriptt>');//shows alert text '</scriptt>' 

Is this some kind of browser error or normal ECMAScript behavior?

(Chrome browser)

+1
source share
3 answers

Since it is considered as follows:

 <script> alert(' </script> '); 

which is a SyntaxError

you can use

 alert( '<\/script>\n'); 
+8
source

The HTML parser does not understand JavaScript and therefore is looking for something to close the </script> . If you need '</script>' as a string in JavaScript, just use '</s'+'cript>' .

JavaScript isself does not have such a problem, using var x = '</script>'; in nodejs is not a problem. HTML parser.

+5
source

This is Javascript embedded in HTML script tags, right?

Then the HTML parser ends your script in the middle.

Put Javascript in your own file or break the string literal. Perhaps the CDATA partition also works.

+1
source

All Articles