JSTL fn:contains() Function

In JSTL, the fn:contains() function is mainly used to check the input substring is present within the given string. This function returns the boolean value representing the result in True or False form.

This function simplifies the substring presence check tasks in Java Server Pages. In this article, we will see the syntax, parameters, and practical example of JSTL fn:contains() function.

Syntax of JSTL fn:contains()

${fn:contains(string, substring)}

Parameters:

  • fn:contains: JSTL expression which will check if the substring is present in the string.
  • string: input string in which the presence of the substring will be checked and the output will be returned in True or False form.
  • substring: substring to check for in the input string.
  • Return Type (boolean): true if the substring is found in the input string or else false is been returned.

Example of fn:contains()

In this example, we will discuss the use of fn:contains(), with two substringsthe one is present and other is not present in the main string.

HTML




<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
    
<html>
  <head>
      <title>Using JSTL Functions</title>
  </head>
  <body>
  <c:set var="mainString" value="Welcome to w3wiki"/>
  <h3>Main String: ${mainString}</h3>
      
  <p>Check for "Beginner": ${fn:contains(mainString, 'Beginner')}</p>
  <p>Check for "Java": ${fn:contains(mainString, 'Java')}</p>
      
  </body>
</html>


Output:

Main String: Welcome to w3wiki 
Check for "Beginner": true
Check for "Java": false

Output Screen of JSTL fn:contains() Program:

Explanation of the above Program:

  • mainString is set to the value “Welcome to w3wiki“.
  • using the fn:contains function we are checking whether the substring “Beginner” is present in the mainString. We have got the result as True because the substring is present in the mainString.
  • Now, check if the substring “Java” is present in the mainString. This condition gives the result as False because the “Java” word is not present in mainString i.e. “Welcome to w3wiki“.
  • We have printed the results using the <p> tag in HTML.


Contact Us