Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lastIndexOf in JSTL or JSP

Tags:

jsp

jstl

Can I figure out lastIndexOf() function at JSTL or JSP ? I just found the method
int indexOf(java.lang.String, java.lang.String) in JSTL. Or has there anyway to work this ?

like image 411
Cataclysm Avatar asked Sep 04 '13 03:09

Cataclysm


3 Answers

can try :

<c:set value="${fn:split('fooBar/BarFoo/Bar','/')}" var="separatorPosition" />
     <c:out value="${separatorPosition[fn:length(separatorPosition)-1]}">
   </c:out>
like image 92
Zigri2612 Avatar answered Nov 17 '22 16:11

Zigri2612


How about using fn:split and sum lengths (fn:length) of all components excluding the last one.
But it's much better to do all logic in backend, just add additional properties to your object.

like image 32
Alex Avatar answered Nov 17 '22 16:11

Alex


Here's one that seems to work for me. Modify myStr and lastIndexOf to what you want.

    <!-- Prepare variables -->
    <c:set var="myStr" value="this_is my. string_ok"/>
    <c:set var="lastIndexOf" value="_"/>
    <c:set var="lastIndexFoundAt" value=""/>
    <c:set var="myStrSize" value="${fn:length(myStr) }"/>
    <c:set var="indexIn" value="0"/>
    <c:set var="indexOut" value="1"/>

    <!-- iterate through string -->
    <c:forEach var="i" begin="0" end="${myStrSize}">

            <c:if test="${indexOut <= myStrSize }">
                <c:set var="char" value="${fn:substring(myStr, indexIn, indexOut) }"/>
                <c:if test="${char == lastIndexOf }">
                    <c:set var="lastIndexFoundAt" value="${i}"/>
                </c:if>

                <c:set var="indexIn" value="${indexIn + 1 }"/> <!-- increment -->
                <c:set var="indexOut" value="${indexOut + 1 }"/> <!-- increment -->
            </c:if>

    </c:forEach>

to test the index, use

    <c:out value="${lastIndexFoundAt}/>
like image 20
blackStrings Avatar answered Nov 17 '22 14:11

blackStrings