In this tutorial we will see fn:join() and fn:split() functions of JSTL.
fn:join()
It concatenates the strings with a given separator and returns the output string.
Syntax
String fn:join(String arrayofstrings, String separator)
It concatenates all the elements of the input array along with the provided separator in between. The return type of this function is String, it returns the output string after concatenation.
Example – Join strings using fn:join() function
In this example we are having an array of strings and we are joining them using the separator (‘ & ‘).
<%@ 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:join() example</title> </head> <body> <% String arr[]={"Chaitanya", "Rahul", "Ajeet"}; session.setAttribute("names", arr); %> ${fn:join(names, " & ")} </body> </html>
Output:
As you can see all the three names got concatenated having ‘ &’ in between.
fn:split()
It splits a given string into an array of substrings. Splitting process considers the delimiter string which we provide during function call. I.e. we provide the string and delimiter as arguments to the function and it returns the array of strings after splitting the input based on the delimiter string.
Syntax
String[] fn:split(String inputstring, String delimiterstring)
Example – Join strings using fn:split() function
In this example we are having a input string which has few space characters in between. We have split the string using space as delimiter using fn:split() function. The function returned the array of the sub-strings.
<%@ 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:split() example</title> </head> <body> <c:set var="msg" value="This is an example of JSTL function"/> <c:set var="arrayofmsg" value="${fn:split(msg,' ')}"/> <c:forEach var="i" begin="0" end="6"> arrayofmsg[${i}]: ${arrayofmsg[i]}<br> </c:forEach> </body> </html>
Output:
Leave a Reply