9

Does anyone know how to truncate a string in a JSP using a tag library? I was going to use Jakarta Taglibs but it says that it has been retired because:

With the advent of JSTL, the core features of many of the libraries had been standardized and the need for these libraries diminished. As such, much of the Taglibs codebase moved into maintenance mode.

bluish
  • 26,356
  • 27
  • 122
  • 180
Justin Wrobel
  • 1,981
  • 2
  • 23
  • 36
  • 3
    Do not read docs of the predecesor of JSTL. Read the real JSTL docs. http://download.oracle.com/javaee/5/jstl/1.1/docs/tlddocs/ – BalusC Jun 20 '11 at 22:18

2 Answers2

20

You can use the JSTL substring function:

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

${fn:substring(myVariable, 0, 5)}
Etienne Neveu
  • 12,604
  • 9
  • 36
  • 59
  • 1
    Note that using JSTL fn:substring(), it is not necessary to check the string length. If too small, this does not give a StringIndexOutOfBoundsException - unlike core Java String.substring(). – Kevin Swann May 18 '18 at 09:18
-1

You can simply use the Java Scriptlets in JSP.
e.g.

<%
    int i = 5; // This is the number of characters to truncate

    String s = "This is a String";

    s = s.substring(0, i);
%>
Sid
  • 4,893
  • 14
  • 55
  • 110