I am trying to get a JSTL <c:forEach>
tag to work so that it would print a list of names as follows:
Best, Milo, Kane
My code is as follows:
<c:forEach items="${persons}" var="person">
${person.name},
</c:forEach>
However, on the last person/name, a comma is inserted at the end, e.g.
Best, Milo, Kane,
How can I avoid the last comma in the loop?
In this example, we first split a comma separate String using forTokens tag by specifying delims=";". When we iterate over tokens, var represent current token. In the second example, we have specified multiple delimiter in delims attribute, delims="|," to split String by pipe(|) character and comma (,) character.
To split a string with comma, use the split() method in Java. str. split("[,]", 0);
The <c:forTokens> tag is used to iterate over a string value separate by a delimiter.
You could use LoopTagStatus#isLast
<c:forEach items="${persons}" var="person" varStatus="loop">
${person.name}
<c:if test="${!loop.last}">,</c:if>
</c:forEach>
A simpler solution is to use a conditional operator within EL
instead of the if
tag
${!loop.last ? ',' : ''}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With