Search code examples
splitjstlretain

JSTL split keep blank or empty strings


I am trying to use JSTL split on a string which has '|' as delimiter. However, if there is no value in between, the split is omitting this in the final array.

eg: abc|def||jkl

i want the array to contain (4 items) 'abc; 'def' '' 'jkl'

but, the split skips the empty value and i get only 3 items.

I know in js we can add the -1 parameter to avoid this issue. How do we solve this in JSTL?

Any help here would be greatly appreciated.


Solution

  • According to the specification, fn:split internally uses StringTokenizer and therefor the behavior is the same as StringTokenizer.

    So I think it is difficult to implemtent only by JSTL. One possible solution is to use java.lang.String.split(). For example, the following code:

    <% request.setAttribute("strings", "abc|def||jkl".split("\\|")); %>
    <c:forEach var="string" items="${strings}" varStatus="status">
    <c:out value="${status.index}"/>:<c:out value="${string}"/>
    </c:forEach>
    

    prints out:

    0:abc 1:def 2: 3:jkl