Last active
November 18, 2015 22:15
-
-
Save NKjoep/3169437 to your computer and use it in GitHub Desktop.
JSP javascript escape with JSTL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%@ 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" /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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"></c:set>
<c:set var="backslashReplaceReplace">\</c:set>