JavaScript Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 2.11

Escaping 'script' Tags in String Literials

This section provides a tutorial example on how to use escape character in 'script' tags to prevent brower prematurely end embedded JavaScript code.

Now let's try to fix the problem we found in the previous section.

The first fix is to use the backslash character (\) to escape (/) in the </script> tag. This extra backslash will stop the browser to recognize this tag as the end of JavaScript code. At the same time, JavaScript engine will ignore this backslash and evaluate the string literal in the same way as without the extra backslash.

Here is the revised HTML document with the extra backslash character:

<html>
<!-- Escape_Script_Tag_Backslash.html
   Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head><title>Escaping Script Tags</title></head>
<body><pre>
<script type="text/javascript">
   document.writeln("Qeustion: How to use the <script> tag?");
   document.writeln("Answer: <script>...Script Code...<\/script>");
   document.writeln("Rate this answer: 1 | 2 | 3 | 4 | 5");
</script>
</pre></body>
</html>

If you run this example script in a browser, you will get:

Qeustion: How to use the 
Rate this answer: 1 | 2 | 3 | 4 | 5

Better? Yes. But this is still not what we expected. Here is what happened when the browser processes this HTML document:

  • The browser correctly skipped the <\/script> and reached the real end of the JavaScript code.
  • The entire JavaScript code is executed correctly without any error.

In another word, there is no code error in the JavaScript code now. The execution of the JavaScript code inserted the following content into the "document" object:

Qeustion: How to use the <script> tag:
Answer: <script>...Script Code...<\/script>
Rate this answer: 1 | 2 | 3 | 4 | 5

When the browser renders this content, it will treat "script" tags as HTML tags, causing some text not showing on the final page.

See the next section on how to protect "script" tags in HTML documents.

Sections in This Chapter

JavaScript Support in Web Browsers

Including JavaScript Codes with HTML "script" Tags

Including 'script' Tags in String Literials

Escaping 'script' Tags in String Literials

Using HTML Entities to Protect HTML Tags

Including JavaScript Codes as External Files

DOM API - The "document" Object

DOM API - The "window" Object

Event Listeners and Objects

'javascript:' Pseudo-URL Addresses

Dr. Herong Yang, updated in 2008
Escaping 'script' Tags in String Literials