In one of our applications we have the following lines:
while (text.indexOf(' ') !== -1)
text = text.replace(' ', '_');
while (text.indexOf('*') !== -1)
text = text.replace('*', 'x');
As far as I know I could also write it like this to avoid the loops:
text = text.replace(/ /g, '_');
text = text.replace(/*/g, 'x');
Which of the two versions would be better programming style? Is there any difference (performance, result, errors, ...) between these two? Do we have to avoid loops if possible?
I noticed that using regex somewhat confuses new (fresh/inexperienced) developers. So, they would find the first option easier to read and grasp what is it doing.
However, the second options is:
As for errors, it does not throw any errors, if you don't make any mistakes in your regex string. Ironically, you did (you should escape special character *). So, here is one reason for choosing option 1 :)
text.replace(/\*/g, 'x');
No brainer - your second option. Don't invoke a loop if you can avoid it. Javascript is a functional language; use it!
An even better solution is to chain them as follows:
text = text.replace(/ /g, "_").replace(/\*/g, "x");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With