Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 646
parkerfath Avatar asked Sep 12 '08 00:09

parkerfath


People also ask

How to break line in Jstl?

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.

What is the use of JSTL function tags?

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.


2 Answers

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, "; ")} 
like image 149
parkerfath Avatar answered Oct 10 '22 09:10

parkerfath


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', ';')} 
like image 33
BalusC Avatar answered Oct 10 '22 09:10

BalusC