Search code examples
javascriptjspquotes

escape possible quotes in string passed to a js function in a onclick event


I have the following cycle in a jspx:

<c:forEach var="var" items="${dataFile.list.rows}">
  <li>
    <div>
      <a href="#" onClick="myFunct('${var.url}','escape(${var.title}),'escape(${var.descr})');">
        <img width="108" height="66" alt="" src="${var.img}" />
      </a>
    </div>
  </li>
</c:forEach>

Where function myFunct does some stuff on its own. My problems arise when either ${var.title} or ${var.descr} contain quotes or double quotes. I can't know in advance whether there's going to be some or which.

I tried the above, I tried a little helper js section just before the element, but not knowing which kind of quotes I'm going to have I can't guess whether I need to put escape("${var.title}"); or escape('${var.title}');.

Any idea on how to solve this? Thanks.


Solution

  • You should do it in the server side, not in the client side. Doing it in the client side is too late anyway. Depending on the sole purpose of the value, whether it's going to be used as part of HTML and doesn't contain linebreaks, or as JS code, you can use either the JSTL-provided EL function fn:escapeXml()

    <%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    ...
    <a onclick="myFunct('${var.url}','${fn:escapeXml(var.title)}','${fn:escapeXml(var.descr)}');">
    

    or create a custom EL function which uses Apache Commons Lang StringEscapeUtils#escapeJavaScript() under the covers.

    <%@taglib prefix="my" uri="http://example.com/functions" %>
    ...
    <a onclick="myFunct('${var.url}','${my:escapeJs(var.title)}','${my:escapeJs(var.descr)}');">
    

    You can find a concrete example how to create an EL function at the bottom of this answer.

    I guess that it's going to be used as part of HTML, so fn:escapeXml() could to be sufficient.