Search code examples
javascriptjquerystripes

Escape single/double quotes from Stripes action bean jquery


I have a javascript function as below,

function check() {
    document.getElementById("customer.name").value = "${actionBean.customer.name}";

.....

}

The value ${actionBean.customer.name} might have ' or "" quotes. How can I escape this from the javascript method?

For eg, the actionBean.customer.name dynamically becomes "HI "I'M HOME""

Cheers!!


Solution

  • org.apache.commons.lang3.StringEscapeUtils can do that for you. It has a method escapeEcmaScript(String input).

    Older versions in org.apache.commons.lang.StringEscapeUtils contain a similar method escapeJavaScript(String input).

    I usually create a StringFunctions class, consisting of static functions, like wrapping the escapeEcmaScript function:

    public static String escapeEcmaScript(String s) {
       return StringEscapeUtils.escapeEcmaScript(s);
    }
    

    Include the StringFunctions class in a tag library descriptor:

    <taglib xmlns="http://java.sun.com/xml/ns/j2ee" version="2.0">  
    
        <tlib-version>1.0</tlib-version>  
        <short-name>tlb</short-name>  
        <uri>http://www.trilobiet.nl/taglib/trlbt</uri>  
    
        <function>    
            <name>escapeEcmaScript</name>    
            <function-class>
                com.trilobiet.apollo.stripes.viewhelpers.StringFunctions
            </function-class>    
            <function-signature>    
                String escapeEcmaScript(java.lang.String)    
            </function-signature>  
        </function> 
    
        <!-- more functions -->
    
    </taglib>
    

    Include the tag lib descriptor in jsp:

    <%@ taglib prefix="tlb" uri="/WEB-INF/taglib/tlb.tld" %>
    

    (Of course you are free to use any short-name and taglib prefix that sound logical to you.)

    And use like so:

    ${tlb:escapeEcmaScript(actionBean.customer.name)}