jspjstljstl-functions

Replace variable amount of characters in JSTL match


I have a text string with 0-5 leading spaces at the beginning of lines that is being displayed in a JSP, and it needs to keep those spaces for indentation

The way the code is currently, it's hard-coded to replace the different lengths of spaces after a line break with   escapes, but is doing this one at a time:

<c:set var="newline" value="\n" />
<c:set var="formattedMessage" value="${item.messageTx}" />
<c:set var="formattedMessage" value="${fn:replace(formattedMessage, newline + '    ', '<br>&nbsp;&nbsp;&nbsp;&nbsp;'}" />
<c:set var="formattedMessage" value="${fn:replace(formattedMessage, newline + '   ', '<br>&nbsp;&nbsp;&nbsp;'}" />
<c:set var="formattedMessage" value="${fn:replace(formattedMessage, newline + '  ', '<br>&nbsp;&nbsp;'}" />
<c:set var="formattedMessage" value="${fn:replace(formattedMessage, newline + ' ', '<br>&nbsp;'}" />
<c:set var="formattedMessage" value="${fn:replace(formattedMessage, newline, '<br>'}" />

It's functional as is, but feels sloppy and inefficient

A simple way that would fix this is replacing all spaces with &nbsp; escapes, but that as well feels unnecessary

Is there a way to do this so it catches the number of spaces after the line break, and replace it with the required amount of escape characters?

If needed, this could be done through the Java code on the server instead


Solution

  • Not sure why it got deleted, but there was an answer posted that fit the use case and bypassed the need for the String parsing altogether

    Setting the element as white-space: pre-wrap maintained the leading spaces without having to replace it with escaped characters

    In summary, JSTL can't effectively do what I was asking without the bloat in the example, so the best solution is to not do it and find another way to maintain the indentation