Skip to content

Instantly share code, notes, and snippets.

@NKjoep
Last active November 18, 2015 22:15
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NKjoep/3169437 to your computer and use it in GitHub Desktop.
Save NKjoep/3169437 to your computer and use it in GitHub Desktop.
JSP javascript escape with JSTL
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%-- setup --%>
<% pageContext.setAttribute("carriageReturn", "\r"); %>
<% pageContext.setAttribute("newLine", "\n"); %>
<c:set var="singleQuotes">'</c:set>
<c:set var="singleQuotesReplace">\'</c:set>
<c:set var="doubleQuotes">"</c:set>
<c:set var="doubleQuotesReplace">\"</c:set>
<c:set var="backslash">\</c:set>
<c:set var="backslashReplace">\\</c:set>
<%-- your string --%>
<c:set var="STRING_TO_ESCAPE">This is only a littl' test, "escape me"!</c:set>
<c:set var="ESCAPED_STRING" value="${
fn:replace(
fn:replace(
fn:replace(
fn:replace(
fn:replace(STRING_TO_ESCAPE, backslash, backslashReplace),
carriageReturn, ' '),
newLine, ' '),
singleQuotes, singleQuotesReplace),
doubleQuotes, doubleQuotesReplace)
}" />
<%-- output --%>
Escaped String: <c:out value="${ESCAPED_STRING}" escapeXml="false" />
@sorin-postelnicu
Copy link

I think you could also insert the following replace as the inner-most replace call (or in any case before the replaceSingleQuotes and replaceDoubleQuotes):

fn:replace(STRING_TO_ESCAPE,backslash,backslashReplace)

where, of course,
<c:set var="backslash">&lt;/c:set>
<c:set var="backslashReplaceReplace">\</c:set>

@NKjoep
Copy link
Author

NKjoep commented Aug 6, 2013

@sorin-postelnicu yeah you're right! also the backslashes need to be replaced. Good one! ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment