Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop to single statement

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?

like image 223
diiN__________ Avatar asked Mar 05 '26 02:03

diiN__________


2 Answers

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:

  • Short and concise, also easy to read (provided, you are familiar with regex);
  • Theoretically it should be faster, since you are letting the native code to do all the heavy lifting, instead of asking it to interpret the looping code an reassigning a string variable. However, the regex has some overhead that may lead to inefficiency. But, it does not apply (noticeable) in real life scenarios, especially in this case.

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');
like image 133
Uzbekjon Avatar answered Mar 07 '26 16:03

Uzbekjon


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");
like image 45
theharls Avatar answered Mar 07 '26 14:03

theharls



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!