How can I replace newline characters using JSP and JSTL?

I have a list of bean objects passed into my JSP page, and one of them is a comment field. This field may contain newlines, and I want to replace them with semicolons using JSTL, so that the field can be displayed in a text input. I have found one solution, but it's not very elegant. I'll post below as a possibility.


Solution 1:

Here is a solution I found. It doesn't seem very elegant, though:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<% pageContext.setAttribute("newLineChar", "\n"); %>

${fn:replace(item.comments, newLineChar, "; ")}

Solution 2:

Just use fn:replace() function to replace \n by ;.

${fn:replace(data, '\n', ';')}

In case you're using Apache's EL implementation instead of Oracle's EL reference implementation (i.e. when you're using Tomcat, TomEE, JBoss, etc instead of GlassFish, Payara, WildFly, WebSphere, etc), then you need to re-escape the backslash.

${fn:replace(data, '\\n', ';')}

Solution 3:

This is similar to the accepted answer (because it is using Java to represent the newline rather than EL) but here the <c:set/> element is used to set the attribute:

<c:set var="newline" value="<%= \"\n\" %>" />
${fn:replace(myAddress, newline, "<br />")}

The following snippet also works, but the second line of the <c:set/> element cannot be indented (and may look uglier):

    <c:set var="newline" value="
" /><!--this line can't be indented -->
    ${fn:replace(myAddress, newline, "<br />")}