Reversing a string using RegExp
Bruce Axtens
Posted on July 23, 2019
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;
}
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.
π πͺ π
π©
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.