JSTL fn:replace() Function
The JSTL fn:replace() function or method in JSP (Java Server Pages) is mainly used for the manipulation of strings. This function allows developers to replace the occurrence of a specified substring with another substring in the given input string. This article will see the Syntax, parameters, and two practical examples of the fn:replace() function. We need to note that the replace function performs case-sensitive processing of string.
Syntax of fn:replace()
${fn:replace(sourceString, targetSubstring, replacementSubstring)}
Where,
- sourceString: This is the input or original string in which the replacement or modification is to be done.
- targetSubstring: This is the substring to be replaced in the sourceString.
- replacementSubstring: This is the substring that will mainly replace occurrences in the targetSubstring in the sourceString.
Example of fn:replace() function
Below is the implementation of the fn:replace() function:
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 >JSTL fn:replace() Example</ title > </ head > < body > < c:set var = "originalString" value="w3wiki is a platform for computer science students. w3wiki is good." /> < p >Original String: ${originalString}</ p > < c:set var = "modifiedString" value = "${fn:replace(originalString, 'w3wiki', 'GFG')}" /> < p >Modified String: ${modifiedString}</ p > </ body > </ html > |
Output:
Original String: w3wiki is a platform for computer science students. w3wiki is good.
Modified String: GFG is a platform for computer science students. GFG is good.
Final Output Shown in the Browser:
Explanation of the above Program:
- In the above example, we have initialised the “originalString” variable with the text.
- Then, we used the “fn:replace()” function to replace the occurrences of “w3wiki” with the “GFG” in the originalString variable.
- The replaced string is been saved in the “modifiedString” variable and we are printing it on screen using <p> tag in HTML.
Contact Us