String reverse prototype function in Javascript

December 27, 2007

Svendtofte.com has a list of useful Javascript prototype methods inspired by functional programming. (Lovely)
But there’s one of his prototype methods that I have an opinion on, his string reverse method:

String.prototype.reverse = function() {
    var s = "";
    var i = this.length;
    while (i>0) {
        s += this.substring(i-1,i);
        i--;
    }
    return s;
}

It’s a classic C style string reverse method. My suggestion is instead this:

String.prototype.reverse=function(){
       return this.split("").reverse().join("");
}

What does it do?
x=”nitro2k01″.reverse() for example does this: this.split(“”) splits the string into an array, where every element is one character of the string. “nitro2k01″ in the example becomes the array ["n","i","t","r","o","2","k","0","1"]. .reverse() in turn reverses the array, so the new array becomes ["1","0","k","2","o","r","t","i","n"]. Lastly .join(“”) turns the new array back into a string, “10k2ortin”, which is returned.

I like my function better because it has a more functional look, re-uses builtin JS functionality and possily is faster. (Although I’ll have to investigate the last claim more thoroughly.)

2 Responses to “String reverse prototype function in Javascript”

  1. m a r c o Says:

    Your single line code function suggestion is nice, I wanted to cjeck its performance : it is highly browser-dependant, faster than “Cstyle” one with FF or IE, but much slower with Chrome…All results here :
    http://fgth98.free.fr/js/benchReverseString2.htm
    Example for a 100Kb string:
    ie7: Cstyle=3690ms JSstyle=137ms
    FF : Cstyle=251ms JSstyle=210ms
    Chrome : Cstyle=21ms JSstyle=91ms
    Regards,
    m a r c o

  2. trenchy Says:

    “foobar”.split(“”).reverse().join(“”);
    //raboof


Leave a Reply