How to escape apostrophe or quotes on a JSP (used by JavaScript)
Use the Apache StringEscapeUtils.escapeJavaScript function.
Escapes the characters in a String using JavaScript String rules. Escapes any values it finds into their JavaScript String form. Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.) So a tab becomes the characters '\\' and 't'.
fn:escapeXml
does not work in JavaScript. It replaces '
with #&0039;
still causing an error when the JavaScript is executed.
Only escaping in the JavaScript manner is correct: \'
The Apache StringEscapeUtils.escapeJavaScript function does this for you. Creating a taglib for it greatly simplifies matters.
I prefer to avoid scriptlets in the middle of my page and was having to use them (increasingly often) to escape strings when used in JavaScript code. I wanted an Expression Language (EL) way of escaping the strings. I created a very small custom taglib that I use for just this purpose:
Utilities.java:
package com.mycom.taglibs;
import org.apache.commons.lang.StringEscapeUtils;
public class Utilities {
public static String escapeJS(String value) {
return StringEscapeUtils.escapeJavaScript(value);
}
}
mytaglib.tld:
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>My Tag Library</description>
<display-name>Tag Utils</display-name>
<tlib-version>1.1</tlib-version>
<short-name>myt</short-name>
<function>
<description>
JavaScript Escape function
</description>
<name>escapeJS</name>
<function-class>com.mycom.taglibs.Utilities</function-class>
<function-signature>java.lang.String escapeJS(java.lang.String)</function-signature>
</function>
</taglib>
And, in the JSP page:
<%@ taglib prefix="myt" uri="/WEB-INF/mytaglib.tld" %>
The escaped string is: ${myt:escapeJS(variableHoldingTheString)}