DEV Community

Bruce Axtens
Bruce Axtens

Posted on • Edited on

4 1

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay