Skip to content
September 29, 2005 / dshuck

Problem: Javascript single quotes from CF variable

On the DFWCFUG list someone asked if anyone had a solution regarding a problem with passing a ColdFusion variable into an agument of a Javascript call when single quotes might exist in the variable, causing the function call to barf.

Someone suggested replacing all single quotes with double quotes.  This however might not be optimal if you are dealing with someone’s name like Conan O”Brian, of if the text was Don”t do this.   I suggested doing the following to avoid this problem.  Assume the following code:

<cfoutput>
onclick=”doIt(‘#ourColdFusionString#’);”
</cfoutput>

If you wanted to make that same function call safe from single quotes, you could do this:

<cfoutput> onclick=”doIt(‘#replace(ourColdFusionString,”‘”,”\’”,”all”)#’);” </cfoutput>

Of course in most cases, it would make more sense to create a user defined function to manage this so you don’t have to continually type the same replace code. Additionally, it would easily allow you to change the rules for what might be safe for your Javascript function.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 591 other followers