Open In App

JSTL fn:indexOf() Function

Last Updated : 14 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

For JSTL-based applications, fn:indexOf() function is used to get the first occurrence index or the position of the substring in the main string. This function-

  • returns the position of the substring if it is found in the main string.
  • If it is not found, then it returns the -1 value and prints on the screen.

In this article, we will see the syntax of this function its parameters, and the example with the output and explanation.

Syntax of fn:indexOf() Function

${fn:indexOf(string, substring)}

where,

  • string: This is the input or specified sting in which we are searching for the substring.
  • substring: This is the string to be located within the input string. If it is found the index is been returned or else the -1 is been returned.

Example of JSTL fn:indexOf() Function

Below is the implementation of JSTL fn:indexOf() Function:

HTML




<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    
<html>
  <head>
      <title>JSTL fn:indexOf() Example</title>
  </head>
  <body>
    <c:set var="inputString" value="Welcome to GeeksforGeeks"/>
    <c:set var="substringToFind" value="Geeks"/>
    <h3>Original String: ${inputString}</h3>
    <h3>Substring to Find: ${substringToFind}</h3>
      
        <c:set var="indexOfSubstring" value="${fn:indexOf(inputString, substringToFind)}"/>
      
    <h3>Index of Substring: ${indexOfSubstring}</h3>
  </body>
</html>


Output:

Original String: Welcome to GeeksforGeeks
Substring to Find: Geeks
Index of Substring: 11

Output Screen of JSTL fn:indexOf() Function:

Output Screen of JSTL fn:indexOf() Function

Explanation of the above Program:

  • we have stored the “Welcome to GeeksforGeeks” value in the inputString variable.
  • Then we are using the fn:indexOf() function to find the first occurrence of the given substring (Geeks) within the inputString.
  • We can see that the first occurent of Geeks substring is at position 11. So the function has returned this value and we printed that value using the HTML tag <p>.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads