Javascript String.reverse and String.translate

10 February 2010 • code | • PermaLink

The comment about obfuscating email addresses led me to look for Javascript functions that reverse a string, or translate characters á la PHP’s strtr() function.

Of course, they don’t exist natively, so here are my versions that extent the String class:

String.prototype.reverse = function() { var str=’‘; for (i=this.length-1;i>=0;i—) { str += this.charAt(i); } return str; }</p> <p>String.prototype.translate = function(from,to) { var sl = this.length; var tl = to.length; var xlat = new Array(); var str = ‘’;</p> <p> if (sl<1 || tl<1) return this;</p> <p> for (i=0; i<256; xlat[i]=i, i++);</p> <p> for (i=0; i<tl; i++) { xlat[ from.charCodeAt(i) ] = to.charCodeAt(i); }</p> <p> for (i=0; i<sl; i++) { str += String.fromCharCode( xlat[ this.charCodeAt(i) ] ); } return str; }</p> <p>var msg = “Hello world!”;</p> <p>alert(msg.reverse());</p> <p>alert(msg.translate(‘lor’,‘gis’));

The code for the translate() method was copied from the PHP source code. If there are more efficient ways to do it, feel free to comment!

Comments

  1. Don’t miss http://blog.stevenlevithan.com/archives/faster-trim-javascript and http://phpjs.org/functions/index :)

    Steve Clay
    11 February 2010, 18:40 • PermaLink
  2. Thanks Steve. I like the analysis of the various trim implementations. I should change the regexes above to /^\s\s*/ and /\s\s*$/ which gives me the same code as trim1() … a good all-around approach.

    The strtr() equivalent at phpjs.org seems like overkill, although it does handle the case where you can pass an array instead of $from and $to strings.

    Colin
    12 February 2010, 11:29 • PermaLink