The following characters could interfere with an HTML or Javascript parser and should be escaped in string literals: <, >, ", ', \,
and &
.
In a script block using the escape character, as you found out, works. The concatenation method (</scr' + 'ipt>'
) can be hard to read.
var s="Hello <\/script>";
For inline Javascript in HTML, you can use entities:
<div onClick="alert('Hello ">')">click me</div>
Demo: http://jsfiddle.net/ThinkingStiff/67RZH/
The method that works in both <script>
blocks and inline Javascript is \uxxxx
, where xxxx
is the hexadecimal character code.
<
–\u003c
>
–\u003e
"
–\u0022
'
–\u0027
\
–\u005c
&
–\u0026
Demo: http://jsfiddle.net/ThinkingStiff/Vz8n7/
HTML:
<div onClick="alert('Hello \u0022>')">click me</div>
<script>
var s="Hello \u003c/script\u003e";
alert( s );
</script>