How can I split a String in Expression Language and take the last element?

10,131

If you are doing it in JSP then try with JSP JSTL function tag library that provide lost of methods as defined here in JavaDoc

Read more here on Oacle The Java EE 5 Tutorial - JSTL Functions

Here is the code to get the last value based on split on dot.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
 ...

<c:set var="string1" value="This.is.first.String." />
<c:set var="string2" value="${fn:split(string1, '.')}" />

<c:set var="lastString" value="${string2[fn:length(string2)-1]}" />

<c:out value="${lastString }"></c:out>

output:

String

Here is one more example

Share:
10,131
Koray Tugay
Author by

Koray Tugay

Crappy software developer who does not like self-promoting profiles.

Updated on June 05, 2022

Comments

  • Koray Tugay
    Koray Tugay almost 2 years

    This is what I am trying but it seems not to work:

    (myStringHere.split(".")[(myStringHere.split(".").length)-1]).concat(text[myStringHere])
    

    The string I have will be something like this:

    com.foo.bar.zar.gar.ThePartIWant
    

    ThePartIWant is what I want to show in the page only.

    I am using Expression Language 2.2

  • Koray Tugay
    Koray Tugay almost 10 years
    I am using Expression Language and I need to get this done in one line.
  • Koray Tugay
    Koray Tugay almost 10 years
    Thanks but does not work: javax.el.ELException: /test/test.xhtml: For input string: "length"
  • Kabulan0lak
    Kabulan0lak almost 10 years
    string result = myStringHere.split(".")[myStringHere.split(".").length - 1]; doesn't work ?!
  • Koray Tugay
    Koray Tugay almost 10 years
    No, does not work: javax.el.ELException: /test/test.xhtml: For input string: "length"
  • Kabulan0lak
    Kabulan0lak almost 10 years
    Maybe if you cast it string result = myStringHere.split(".")[((string[])myStringHere.split(".")).‌​length - 1]; ?