↑
Main Page
JavaScript functions
alert(sJavaScriptHello);
</script>
This example uses JSP with the intent of outputting the string
“Hello”
into a JavaScript variable. When
this page gets to the browser, you can view the source:
<script type=”text/javascript”>
var sJavaScriptHello = “Hello”;
alert(sJavaScriptHello);
</script>
The output looks correct and the JavaScript functions as expected. But now consider another example:
<% String sJspHeSaidHi = “He said, \”hi.\””; %>
<!-- more code here -->
<script type=”text/javascript”>
var sJavaScriptHeSaidHi = “<%= sJspHeSaidHi %>”;
alert(sJavaScriptHeSaidHi);
</script>
The output to the browser now becomes this:
<script type=”text/javascript”>
var sJavaScriptHeSaidHi = “He said, “hi.””;
alert(sJavaScriptHeSaidHi);
</script>
Do you see the problem? The string that was outputted from the JSP contained quotation marks, which
creates a syntax error in JavaScript. This is the most common mistake made when internationalizing
Web pages that use JavaScript to output strings. You must be aware of quotation marks contained within
strings if the string is to be output into JavaScript code. The best way to deal with this is to replace the
quotation marks in all strings before outputting to JavaScript, such as in the following:
<% String sJspHeSaidHi = “He said, \”hi.\””; %>
<!-- more code here -->
<script type=”text/javascript”>
var sJavaScriptHeSaidHi = “<%= sJspHeSaidHi.replaceAll(“\\\””, “\\\””) %>”;
alert(sJavaScriptHeSaidHi);
</script>
This example converts all quotation marks to a backslash followed by a quotation mark using the Java
replaceAll()
method. The first argument is a string representation of a regular expression (you’ll
remember that regular expression strings must be double-escaped, so
\”
becomes
\\\”
); the second
argument is identical, although this one is a string and not a regular expression. This effectively changes
this string:
“He said, \”hi.\””
572
Chapter 19
22_579088 ch19.qxd 3/28/05 11:43 AM Page 572
Free JavaScript Editor
Ajax Editor
©
→