In this tutorial we will discuss fn:substring (), fn:substringAfter() and fn:substringBefore() functions of JSTL. All of these functions are used for getting a part of the string from a given input string. The way of getting the output is different in all three functions.
fn:substring ()
This function returns a substring of given input string as per the given start and end position.
Syntax
String fn:substring(String inputstring, int start, int end)
- Return type of function: String
- inputstring: The string from which a substring needs to be taken
- start: Starting position of substring
- end: end position of substring
Example – fn:substring() function
In this example we are fetching a substring from a given string by providing the starting and end positions of the substring.
<%@ 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>JSTL fn:substring() example</title> </head> <body> <c:set var="msg" value="This is an example of JSTL function"/> ${fn:substring(msg, 10, 26)} </body> </html>
Output:
fn:substringAfter()
It returns the part of a given string which lies after a provided string value.
Syntax
String fn:substringAfter(String input, String afterstring)
Whatever is present in the input after the “afterstring” is being returned by this function. Refer the below example to have the more clarity on this topic.
Example of fn:substringAfter()
<%@ 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>JSTL fn:substringAfter() example</title> </head> <body> <c:set var="name" value="Rahul Pratap Singh"/> ${fn:substringAfter(name, "Pr")} </body> </html>
Output:
fn:substringBefore()
It is just opposite of fn:substringAfter function. It returns the the part of original string which lies before a specified string value.
Syntax
String fn:substringBefore(String input, String beforestring)
The part of “input” before the “beforestring” will be returned as the output of this function
Example of fn:substringBefore()
<%@ 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>JSTL fn:substringBefore() example</title> </head> <body> <c:set var="justastring" value="Hi, How are you??"/> ${fn:substringBefore(justastring, "are")} </body> </html>
Output:
Leave a Reply