The replace() Function is used to replace a substring with the new one.
<html> <body> <script> var x = "Hello Beautiful World" var y = x.replace("Beautiful", "Wonderful") document.write(y) </script> </body> </html>
In the above code, we have declared a String Hello Beautiful World and assigned it to a variable x.
var x = "Hello Beautiful World"
And we would be replacing Beautiful with Wonderful, from the String, Hello Beautiful World.
So, we have used the replace() Function to replace Beautiful with Wonderful.
var y = x.replace("Beautiful", "Wonderful")
As we can see, there are two parameters in the replace("Beautiful", "Wonderful") function.
And thus the substring Beautiful is searched in the String, Hello Beautiful World. When found, Beautiful is replaced with Wonderful.
And the new String becomes,
Hello Wonderful World
Now, let us say, we have the below String,
"The Beautiful world is Beautiful indeed"
And you are just suppose to change the first substring Beautiful with Wonderful.
Something like the below,
"The Beautiful world is Beautiful indeed"
To solve this, there is a third parameter used by replace() function that says how many occurrence that needs to be replaced.
Let us see with the below example.
<html> <body> <script> var x = "The Beautiful world is Beautiful indeed" var y = x.replace("Beautiful", "Wonderful", 1) document.write(y) </script> </body> </html>
So, if you see the above output, only the first occurrence of Beautiful is replaced withWonderful.
That is because of the below line,
var y = x.replace("Beautiful", "Wonderful", 1)
Where we have specified the third parameter as 1.
Which says that only replace 1 occurrence of the word Beautiful.
And thus we got the output,
The Beautiful world is Beautiful indeed