How to escape apostrophe or quotes on a JSP (used by JavaScript)

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:

package com.mycom.taglibs;

import org.apache.commons.lang.StringEscapeUtils;

public class Utilities {
    public static String escapeJS(String value) {
        return StringEscapeUtils.escapeJavaScript(value);


<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns=""

  <description>My Tag Library</description>
  <display-name>Tag Utils</display-name>

        JavaScript Escape function
    <function-signature>java.lang.String escapeJS(java.lang.String)</function-signature>

And, in the JSP page:

<%@ taglib prefix="myt" uri="/WEB-INF/mytaglib.tld" %>
The escaped string is: ${myt:escapeJS(variableHoldingTheString)}

Leave a Comment