HowCanIescapeOutQuotationMarksFromAStringWithVelocity

Last modified by Vincent Massol on 2006/12/10

Question How can I escape out quotation marks from a string with Velocity?
Answer An XWiki document can potentially contain a line of code that includes all of:
  • Radeox syntax
  • Velocity template syntax
  • Javascript code
Consequently, figuring out escape characters can be a nightmare. Imagine you want to pass a velocity string into Javascript code, e.g.:
<a href=" javascript:alert('\$myVar');">ClickMe</a>

The example above will fail if $myVar contains single or double quotation marks, because the browser wont't parse the HTML+Javascript code as intended. We need to escape out the quotes by preceding them with 1 backslash in the Javascript string.

But to do so at the Velocity level requires 6 (six!) backslashes in each Replace expression. In Velocity it takes 3 backslashes to represent 1 backslash, and we need to represent 2 in our Replace string in order to get 1 in our final Javascript string.

Code

1.1.1 Fixing quotes with velocity
\#set(\$bad="I'm alive.")
\#set(\$good=\$bad.replaceAll("'","\\\\\\\\\\\\\\\\\\'").replaceAll('"','\\\\\\\\\\\\\\\\\\"'))
Strings as perceived by the browser:
* Original: \$bad 
* Processed: \$good
<br>
Test the Javascript:
* <a href=" javascript:alert('\$bad');">Click me - Javascript Error</a>
* <a href=" javascript:alert('\$good');">Click me - Javascript OK</a>

Incidentally, displaying the code above correctly in this page required 18 backslashes for each replace. The {pre} tags didn't seem to help.

Result

Fixing quotes with velocity

Strings as perceived by the browser:

  • Original: I'm alive.
  • Processed: I\'m alive.

Test the Javascript:
Tags:
Created by Robin Fernandes on 2006/04/22
   

Get Connected