3

This :

<script type="text/javascript">
var a = new Array("</script>");
alert(a);
</script>

...doesn't work as expected (by me at least). The string "</script>" is interpreted as the end of the script even though it's in quotes. Please see these jsfiddles :

http://jsfiddle.net/RYbTS/

http://jsfiddle.net/PB73z/

The first declares the first element of the array in the normal way while the second declares it in a compact form. In both cases, browsers (Chrome, FF, IE) stop the script at "</script>" and never get to the alert.

It behaves the same way whether using quotes or double quotes.

Is it expected ? Is there a workaround?

Edit: thanks all, I'll escape the backslash. Sorry I couldn't accept everyone's answer, I accepted the first one, but thanks to everyone.

The link provided by Juhana explains this behavior:

all the HTML is parsed before the text nodes in the element are passed to the JS engine, </script> gets no special treatment for being inside a JS string literal

Michel MM
  • 33
  • 4

3 Answers3

3

You could escape the / character:

<script type="text/javascript">
var a = new Array("<\/script>");
alert(a);
</script>

Here's an updated fiddle.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
2

Escape the sequence:

var a = new Array("<\/script>");

or split it:

var a = new Array("</scr" + "ipt>");

This is why json encode escapes the /. Usually there no need to escape it, but this is (I think) the only case where you run into problems. It would of course be more accurate to escape the sequence </script> but that may seem a little unexpected.

Halcyon
  • 57,230
  • 10
  • 89
  • 128
1

use as follows :

<script type="text/javascript">

var a = new Array("<\/script\>");
alert('ok');

</script>

fiddle here :

http://jsfiddle.net/GUc2x/

Sunil Verma
  • 2,490
  • 1
  • 14
  • 15