DEV Community

Bruce Axtens
Bruce Axtens

Posted on • Updated on

Reversing a string using RegExp

Just when you thought it was safe to go out, here's another take on reversing a string: using RegExp object.

function Bruce_RegReverse(string) {
  let res = "";
  const re = /^(.)(.*$)/;
  while (string !== "") {
    const match = re.exec(string);
    if (null !== match) {
      res = match[1] + res;
      string = match[2];
    }
  }
  return res;
}
Enter fullscreen mode Exit fullscreen mode

The naming here reflects that I've put it into my testing framework. The results indicate that you shouldn't use RegExp to reverse at string, or at least not like the above: In a run that saw Sarah Chima's Sarah_SplitReverseJoin take an average of 2551.8 ticks, Bruce_RegReverse took an average of 500494.9 ticks.

Top comments (1)

Collapse
 
elmuerte profile image
Michiel Hendriks

😅

I'm looking for the next person to one-up this and maybe create an enterprise version of it with abstract factories and stuff.