JSTL Function fn:indexOf()

The <fn:indexOf()> is a string function of JSTL. This function returns the index within a string of a specified substring. This function is used to get the first occurrence of the substring in the given string. This function takes string type as arguments and returns int type.

Syntax of <fn:indexOf()> Tag

      int indexOf(String,String)

Example

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

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

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

<html>

<head>

<title>Example of fn:indexof tag of JSTL</title>

</head>

<body>

	<form method="POST">

		This will calculate the first occurance of given character/string in
		the <br>specified String.

		<table>

			<tr>

				<td>Enter Text</td>

				<td><input type="text" name="text"></td>

			</tr>

			<tr>

				<td>Search</td>

				<td><input type="text" name="str"></td>

			</tr>

			<tr>

				<td></td>

				<td><input type="submit" value="search"></td>

			</tr>

		</table>

	</form>

	<c:if test="${pageContext.request.method=='POST'}">

		<c:set var="text" value="${param.text}" />

		<c:set var="str" value="${param.str}" />

		<font size="3" color="Red"> Index of first occurance : </font>
		<font size="3" color="Blue"> <c:out
				value="${fn:indexOf(text,str)}" />

		</font>

	</c:if>

</body>

</html>

Steps for Execution

  • Save this file as example.jsp in your eclipse IDE.
  • Now select this jsp file, right mouse click and select Run as ->Run on server

Output

When the execution process is completed successfully we will get the following output :
Suppose if we enter the string Javabeat and if we want to index of the first occurrence of the “a” then it will shows the following output.
output of jstl function fn indexOf1
When we enter the string Javabeat and if we press search button it will shows the following output:
output of jstl function fn indexOf2

Previous Tutorial :  JSTL Function fn:escapeXml()   :: Next Tutorial : JSTL Function fn:join()

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*