How can I replace newline characters using JSP and JSTL?

前端 未结 14 1903
遥遥无期
遥遥无期 2020-12-02 22:15

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

相关标签:
14条回答
  • 2020-12-02 23:06

    More easily:

    <str:replace var="your_Var_replaced" replace="\n" with="Your ney caracter" newlineToken="\n">${your_Var_to_replaced}</str:replace>  
    
    0 讨论(0)
  • 2020-12-02 23:08

    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, "; ")}
    
    0 讨论(0)
  • 2020-12-02 23:11

    \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.

    0 讨论(0)
  • 2020-12-02 23:14

    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', ';')}
    
    0 讨论(0)
  • 2020-12-02 23:15

    This is a valid solution for the JSP EL:

    "${fn:split(string1, Character.valueOf(10))}"
    
    0 讨论(0)
  • 2020-12-02 23:17

    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.

    0 讨论(0)
提交回复
热议问题