. I tried ${fn:replace(someString, '\n', '
')} ...">

Replace "\ n" in EL

In the JSP file, I want to replace the newline ( \n ) lines with <br /> . I tried

 ${fn:replace(someString, '\n', '<br />')} 

But I get the error '\n' ecnountered, was expeting one of...

I think this means that the parser does not like something like this.

Is it possible to do something similar with EL?

+6
source share
3 answers

Create an EL function for this.

First create a static method that performs the desired task:

 package com.example; public final class Functions { private Functions() {} public static String nl2br(String string) { return (string != null) ? string.replace("\n", "<br/>") : null; } } 

Then create /WEB-INF/functions.tld , which looks like this:

 <?xml version="1.0" encoding="UTF-8" ?> <taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" version="2.1"> <tlib-version>1.0</tlib-version> <short-name>Custom_Functions</short-name> <uri>http://example.com/functions</uri> <function> <name>nl2br</name> <function-class>com.example.Functions</function-class> <function-signature>java.lang.String nl2br(java.lang.String)</function-signature> </function> </taglib> 

Finally, use it as follows:

 <%@taglib uri="http://example.com/functions" prefix="f" %> ... ${f:nl2br(someString)} 

See also:

+8
source

Your path is much simpler. Why I did not think about it. Here is a demo page.

 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <c:set var="newLine" value="\n" /> <c:set var="myText" value="one\ntwo\nthree" /> ${fn:replace(myText, newLine, '<br/>')} 
+2
source

For me, it worked by first defining the newLine variable, or using

 <% pageContext.setAttribute("newLine", "\n"); %> 

or

 <c:set var="newLine" value="<%= '\n' %>" /> 

And then

 ${fn:replace(someString, newLine, '<br/>')} 
0
source

All Articles