3

How can I loop through each character in a String using JSTL?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Viren Pushpanayagam
  • 2,397
  • 6
  • 35
  • 39

3 Answers3

11

Tricky use of fn:substring() would do

<c:forEach var="i" begin="0" end="${fn:length(str)}" step="1">
    <c:out value="${fn:substring(str, i, i + 1)}" />     
</c:forEach>
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
jmj
  • 237,923
  • 42
  • 401
  • 438
  • Nice - wasn't sure what functions were available – Dave G May 12 '11 at 12:33
  • @Dave you can check all at [javadoc](http://download.oracle.com/docs/cd/E17802_01/products/products/jsp/jstl/1.1/docs/tlddocs/fn/tld-summary.html) – jmj May 12 '11 at 12:35
  • I meant that I didn't remember off the top of my head, was busy this morning and didn't check the ref docs :-) – Dave G May 12 '11 at 17:31
1

Late to the party, but EL 2.2 allows for instance method calls (more on that here: https://stackoverflow.com/a/7122669/2047962). This means that you could shorten Jigar Joshi's answer by a few characters:

<c:forEach var="i" begin="0" end="${fn:length(str)}" step="1">
  <c:out value="${str.charAt(i)}" />     
</c:forEach>

I only suggest this because it is a little more obvious what your code is doing.

Community
  • 1
  • 1
RustyTheBoyRobot
  • 5,891
  • 4
  • 36
  • 55
0

i think you can't do that with JSTL's forEach. You need to write your own tag or an EL function. Here is a sample code how you write your custom tags: http://www.java2s.com/Tutorial/Java/0360__JSP/CustomTagSupport.htm

Erhan Bagdemir
  • 5,231
  • 6
  • 34
  • 40
  • Why not? http://download.oracle.com/docs/cd/E17802_01/products/products/jsp/jstl/1.1/docs/tlddocs/fn/tld-summary.html I see a length function and a substring function here – stivlo May 12 '11 at 12:05
  • fn:substring/fn:length are still EL functions! – Erhan Bagdemir May 12 '11 at 12:06
  • I thought it was bad practice to mix scriptlets with JSTL, while EL should be elegant. Do you mean that EL is not strictly part of JSTL? – stivlo May 12 '11 at 12:10
  • It is true. To use scriptlets in view (jsps) is even worst practice. For that reason you can develop your own custom tags or EL functions. example for custom JSTL tag: – Erhan Bagdemir May 12 '11 at 12:23