How to escape double quotes in JSTL function / EL?

It doesn't work because the \ is an escape character in Java string. To represent it literally, you need to escape it with another \ again. Also the " is a special character in EL, you also need to escape it to represent it literally. So, the proper syntax would have been:

<input type="hidden" name="text" size="40" value="${fn:replace(text, '\"', '\\\"')}">

But, you should actually be using fn:escapeXml() to prevent XSS. It not only escapes quotes, but also other characters.

<input type="hidden" name="text" size="40" value="${fn:escapeXml(text)}">

###See also:

  • XSS prevention in JSP/Servlet web application

You are doing it wrong (with fn:replace).

The correct way is:

<input type="hidden" name="text" size="40" value="<c:out value='${text}'/>">
(actually tested code - works 100%)

Edit: Upon more thinking:

  • the way by using fn:escapeXml (as written by BalusC) works too and looks nicer (no nested tags)
  • using fn:replace to mimick fn:escapeXml is asking for trouble. You will forget to include some character that should be escaped. Just use the existing, tried and tested fn:escapeXml (or c:out)

Tags:

Java

Jstl

El