Reversing a string using RegExp

bugmagnet

Bruce Axtens

Posted on July 23, 2019

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.

πŸ’– πŸ’ͺ πŸ™… 🚩
bugmagnet
Bruce Axtens

Posted on July 23, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related