This post helps you understand how to use the <fn:trim> tag in the JSTL function tags library with code example.

The fn:trim function removes the empty spaces from both ends of a string.

 

JSTL <fn:trim> Syntax:

${fn.trim(<string or var>)}

 

JSTL <fn:trim> Example:

The following JSP example removes the empty spaces of a string from both ends. Note that in order to see the difference before and after the trim, we are displaying the length of the string.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>fn:trim Demo</title>
  </head>
  <body>
	<h1>fn:trim Demo</h1>
		
	<c:set var="text" value="    Sample text    " />
	<p>Original text before trim: <strong><c:out value="${text}"/></strong>	
	<p>Length of text before trim: ${fn:length(text)}</p>

	<c:set var="trimmedText" value="${fn:trim(text)}" />
	<p>Original text after trim: <strong><c:out value="${trimmedText}"/></strong>
	<p>Length of text after trim: ${fn:length(trimmedText)}</p>	
  </body>
</html>

 

Output:

JSTL function fn-trim

 

Other JSTL Function Tags:

contains  |  containsIgnoreCase  |  endsWith |  escapeXml  |  indexOf  |  join  |  length  |  replace  |  split  |  startsWith  |  substring  |  substringAfter  |  substringBefore  |  toLowercase  |  toUpperCase


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment