Tuesday, August 5, 2008

JavaScript String Reversal

I was just surfing through some snippets when I came across some code for string reversal in JavaScript. Often people post code without having tested it themselves, which is just wrong!!! Here's a snippet I saw when going through one of these posts:
//NOTE: Non-functional JS code for string reversal
for (var i = 0; i < middle; i++) {
var temp = thestring[i];
thestring[i] = thestring[last-i];
thestring[last-i] = temp;
}
Now, one basic thing most people don't realize is that in JavaScript, individual characters of a string cannot be altered by using just the indexes. The above piece of code leaves the string unaltered not throwing any exceptions. The assignment to the individual characters is just ignored and "thestring" remains unchanged. Tested this in FF2, IE7 and Opera 9.51 and they all yielded the same result.

Since string reversal is a very common operation, it could be added to the String prototype if it makes sense. The following snippet does the job quite well, using two very useful functions available to arrays, reverse and join.
/* Full credit to Shachi Bista
http://www.bytemycode.com/snippets/snippet/400 */
String.prototype.reverse = function(){
splitext = this.split("");
revertext = splitext.reverse();
reversed = revertext.join("");
return reversed;
}
Now I prefer to always explicitly declare variables before using them. In this case, "splitext" and "revertext" become global members and could affect other variables that have the same name. Thus, to keep it localized, always explicitly declare the variable within the functions unless you want it to be available everywhere. So here's my revised version of it:
String.prototype.reverse = function(){
var splitext = this.split("");
var revertext = splitext.reverse();
return revertext.join("");
}
If you have a different approach or find a bug in my logic, do let me know.

Cheers.

No comments: