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.
If you need to separate two statements in JavaScript, they can be separated with a semi-colon instead of a new line; might be worth a try. Actually I need to put a \n after a // <! [CDATA[ to end the comemnt before actaul JS code starts. This is already the default behaviour.
JSTL stands for JSP Standard Tag Library. JSTL is the standard tag library that provides tags to control the JSP page behavior. JSTL tags can be used for iteration and control statements, internationalization, SQL etc.
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, "; ")}
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', ';')}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With