Basic Syntax of Replace Method
For more detail about the string replace method click here.
let name = "JS Startup";
Now, we use a replace method and replace a “JS” with “Node” and print it’s value using console log.
Now, we again use a replace method and replace a “Node” with “React” and same print the value with console log.
Any idea, what should be the output of above statement.
let name = "JS Startup"; console.log(name.replace("JS", "Node")); // output => "Node Startup" console.log(name.replace("Node", "React")); // output => 🧐 ? // Made with ❤️, by @jsstartup
Finally, you know the answer is “JS Startup“. But why, doesn’t it should replace with “React“. Let me explain.
InShort, the reason is that replace does not modify the origin string.
Due to which, when we replace a “JS” with “Node”. Then, str value is still “JS Startup”.
So, when we apply the replace method again to replace “Node” with “React” but “Node” not exist in str value. That’s why it return the original string.
At last, That’s why we get an answer “JS Startup”
Let me know in the comment section, what you think about it.
I hope you understand the concept and logic behind it.
But wait, i have something more for you –
- JS Quiz – for loop iterate array in two ways
- JS Quiz – array element duplicate count with for loop
And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page
If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.