As the name of this method says, this method is going to help us replace some pattern inside the string, with another replacement. The pattern can be some string or some regular expression.
If we have the string as a pattern for replacing, then, only the first occurrence of that string would be replaced.
It returns a new string that is modified. If you want to replace something which is not even there in the string, then you will see no change, because there is nothing to be replaced. Note that the original string is left unchanged.
You can refer to the below program which explains the replacement method →
As you can see, we have a string in the program, and we are calling the replace method for the string. Now, we are trying to replace the string ‘GyaniPandit’ with another string ‘something’.
So, the replace method is going to return the new string with the effective changes, and the original string is going to be as it was.
You can simply see that in the below line, we are getting the original string too, onto the console.
Let’s have a look at the output now –
The output shows that the string in the variable str is as it was. So the replace method has returned the new string with the changes. You can try using this method so that you can get familiar with it, and also, remember that since we are using the string pattern, only the first occurrence is going to be replaced.