String replaceAll Method –
Previously, replace method is used but it only replace first matching string but not other. For replace all matching string you have to pass regex.
But that not the case with the replaceAll() string method but it still supports regex also.
It’s syntax looks like –
const newStr = str.replaceAll(regexp|substr, newSubstr|function)
let name = “JS Startup”;
In the second step, we create an another variable string using let and assign the string return from string replaceAll method.
let string = replaceAll(“t”,”i”);
Above, we are going to replace substring “t” with “i“.
Finally, we are checking the output of string using console log.
Any idea what should the output of it.
So, Finally you know the answer is “JS Siariup“. But why, didn’t previously it replace the first occurrence only. Let me explain.
First, it a string replaceAll method not a replace method. In the replace method, we need to pass regex if you want to replace all matching substring.
But replaceAll method, replace all the matching string without any regex. It’s a new method which is introduced.
At last, That’s why we get an answer “JS Siariup“.
Let me know in the comment section, any alternative of it.
I hope you understand the concept and logic behind it.
But wait, i have something more for you –
- JS Quiz – can reduceRight method really sum an array elements
- JS Quiz – includes method can really remove duplicates with forEach
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.