The replace() method replaces each matching occurrence of a character/text in the string with the new character/text.
Example
replace() Syntax
The syntax of the replace() method is either
string.replace(char oldChar, char newChar)
or
string.replace(CharSequence oldText, CharSequence newText)
Here, string is an object of the String class.
replace() Parameters
To replace a single character, the replace() method takes these two parameters:
- oldChar - the character to be replaced in the string
- newChar - matching characters are replaced with this character
To replace a substring, the replace() method takes these two parameters:
- oldText - the substring to be replaced in the string
- newText - matching substrings are replaced with this string
replace() Return Value
- The
replace()method returns a new string where each occurrence of the matching character/text is replaced with the new character/text.
Example 1: Java String replace() Characters
Note: If the character to be replaced is not in the string, replace() returns the original string.
Example 2: Java String replace() Substrings
Note: If the substring to be replaced is not in the string, replace() returns the original string.
It is important to note that the replace() method replaces substrings starting from the start to the end. For example,
"zzz".replace("zz", "x") // xz
The output of the above code is xz, not zx. It's because the replace() method replaced the first zz with x.
If you need to replace substrings based on a regular expression, use the Java String replaceAll() method.