In this post we are discussing two functions which operates on strings. These functions are fn:trim() and fn:startsWith(). Function fn:trim() removes spaces from beginning and end of a string and fn:startsWith() checks whether the specified string is a prefix of given string.
JSTL fn:trim() Function
It removes the space characters from start and end of the provided string.
Syntax:
String fn:trim(String input)
The function returns the string after removing the white spaces from start and end of the input String.
Example
In this example we have a string which has few space characters appended at the start and end of the string “mymsg” and we are truncating those spaces using the function.
<%@ 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>fn:trim() example in JSTL</title> </head> <body> <c:set var="mymsg" value=" This is the test String "/> ${fn:trim(mymsg)} </body> </html>
Output Screenshot:
fn:startsWith() function in JSTL
It checks whether the given string starts with a particular string value.
Syntax:
boolean fn:startsWith(String input, String prefix)
This function returns a boolean value. It gives true when the string starts with the given prefix else it returns false.
Example
Here we have one long string and two substrings of it and we are checking whether the string starts with any of those substrings.
<%@ 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>fn:startsWith example</title> </head> <body> <c:set var="mymsg" value="Example of JSTL function"/> The string starts with "Example": ${fn:startsWith(mymsg, 'Example')} <br>The string starts with "JSTL": ${fn:startsWith(mymsg, 'JSTL')} </body> </html>
Output: PFB the output screenshot for above example.
Leave a Reply