Javascript String.reverse and String.translate

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;
}


String.prototype.translate = function(from,to) {
	var sl = this.length,
		tl = to.length,
		xlat = new Array(),
		str = '';

	if (sl<1 || tl<1) return this;

	for (i=0; i<256; xlat[i]=i, i++);

	for (i=0; i<tl; i++) {
		xlat[ from.charCodeAt(i) ] = to.charCodeAt(i);
	}

	for (i=0; i<sl; i++) {
		str += String.fromCharCode( xlat[ this.charCodeAt(i) ] );
	}

	return str;

}

var msg = 'Hello world!';
alert(msg.reverse());
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!

2 Responses to Javascript String.reverse and String.translate

  1. 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.