Open In App

JSTL fn:replace() Function

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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="GeeksforGeeks is a platform for computer science students. 
                                   GeeksforGeeks is good." />
<p>Original String: ${originalString}</p>
<c:set var="modifiedString" value="${fn:replace(originalString, 'GeeksforGeeks', 'GFG')}"/>
<p>Modified String: ${modifiedString}</p>
</body>
</html>

Output:

Original String: GeeksforGeeks is a platform for computer science students. GeeksforGeeks is good.
Modified String: GFG is a platform for computer science students. GFG is good.

Final Output Shown in the Browser:

Output_of_of-fn:replace()-function

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 "GeeksforGeeks" 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.

Next Article

Similar Reads