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
More easily:
<str:replace var="your_Var_replaced" replace="\n" with="Your ney caracter" newlineToken="\n">${your_Var_to_replaced}</str:replace>
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, "; ")}
\n does not represent the newline character in an EL expression.
The solution which sets a pageContext
attribute to the newline character and then uses it with JSTL's fn:replace
function does work.
However, I prefer to use the Jakarta String Tab Library to solve this problem:
<%@ taglib prefix="str" uri="http://jakarta.apache.org/taglibs/string-1.1" %>
...
<str:replace var="result" replace="~n" with=";" newlineToken="~n">
Text containing newlines
</str:replace>
...
You can use whatever you want for the newlineToken; "~n" is unlikely to show up in the text I'm doing the replacement on, so it was a reasonable choice for me.
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', ';')}
This is a valid solution for the JSP EL:
"${fn:split(string1, Character.valueOf(10))}"
You should be able to do it with fn:replace.
You will need to import the tag library into your JSP with the following declaration:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
Then you can use the following expression to replace occurrences of newline in ${data} with a semicolon:
${fn:replace(data, "\n", ";")}
The documentation is not great on this stuff and I have not had the opportunity to test it.