How do I make sure a string is safe to use with JavaScript?

If you are dynamically populating a JavaScript variable, you may find that your code breaks with "unterminated string constant" or similar error messages. This is probably a case of your JavaScript variables containing characters that are considers to be "special" characters by JavaScript. You will need to "escape" these special characters so that JavaScript can process them.

Some common characters you need to be wary of include: newlines, carriage returns, and quotes. In order for JavaScript to handle these special characters, they must be escaped, or converted to JavaScript safe alternatives. JavaScript makes use of the \ characters to escape most special characters.

The following code sample from the CF Docs shows how to use the ColdFusion jSStringFormat() function to make a string JavaScript safe:

<cfset stringValue = "An example string value with a tab chr(9), a newline (chr10) and some ""quoted"" 'text'">
<p>This is the string we have created:<br>
<cfset jsStringValue = jSStringFormat(#stringValue#)>
<!----- Generate an alert from the JavaScript string jsStringValue. ---->
s = "<cfoutput>#jsStringValue#</cfoutput>";

This question was written by Jeremy Petersen
It was last updated on March 29, 2006.




comments powered by Disqus