2

If I add this piece of html to my page:

<script type="text/javascript">
 var s = '</script>'
</script>

IE 7.0 shows a syntax error (exclamation mark in left bottom corner): "Unterminated string constant"

if I change just one letter (any) the error disappears - looks like IE doesn't like this particular word, including brackets.

Any ideas why?

Thank you, Andrey

5 Answers 5

8

This works for me

var a = "<\/script>"
Sign up to request clarification or add additional context in comments.

3 Comments

You can should also be able to wrap your code in <!-- --> (or <![CDATA[ ]]> if it's being parsed as X(HT)ML).
You should NOT wrap the code in <!-- -->. We don't need to cater for Netscape 2 any more.
Neither should you wrap your code in <![CDATA[..]]> without commenting it out. <![CDATA[..]]> is an XML literal in JavaScript 1.6+ and nothing in it would be processed as code
6

This will happen for any browser. The HTML parser does not know the details of the scripting language you're trying to use, so your <script> tag will be terminated on the first occurence of </script>, regardless of context. The JS parser will then of course complain that the string is not terminated, because the closing apostrophe is not inside the script block.

You need to use something like '<\/script>' instead if you want to use that scring in your script.

6 Comments

Would the downvoters care to elaborate on their reasons for doing so?
IIRC, it is "</" that terminates SCRIPT tag.
I would consider an HTML parser that worked like that as being broken. since that goes against all other HTML principles - </> might break it as well due to its property as an "anonymous close tag" in SGML, but most certainly not </.
Having said that, I have not exhaustively tested all browsers for this, but IE 8 certainly doesn't behave like that.
I'm not familiar with SGML rules in this regard, but I just checked again and HTML does indeed explicitly state that "</" is what terminates SCRIPT (other than that sequence, element's contents are just plain CDATA) - w3.org/TR/REC-html40/types.html#type-cdata
|
3

To use a / character you need to first preface it with \.

So this works:

<script type="text/javascript"> var s = '<\/script>'; alert( s);</script>

Comments

1

I've seen this...

var s = '</scr' + 'ipt>'

That said, it gives off a bit of a code smell. I'm not sure if it's appropriate. :)

1 Comment

I find it amusing that the other answer that had string concatenation in it was upvoted, while this one was down voted.
0

I've seen this:

var s = unescape("%3C/script%3E")

Smells really bad too.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.