Transliterate in JavaScript

| | Comments (0) | TrackBacks (0)

While chatting with a fellow developer friend today talking about how insanely cool JavaScript actually is he mentioned one function he missed was transliteration (as in the tr operation in Perl).

So I whipped up the following function:


String.prototype.tr = function(from, to) {  
    var fromChars = from.split("");  
    var toChars = to.split("");  

    var mapTable = {};  

    for(i = 0; i < fromChars.length; i++) {  
        var c = i < toChars.length ? toChars[i] : "";  
        mapTable[fromChars[i]] = c;  
    }  

    var str = this;  

    var re = new RegExp(fromChars.join("|"), "g");  
    str = str.replace(re, function(c) { 
        return mapTable[c]; 
    });  

    return str;  
};

Maybe not the fastest nor safest but it does the job =)

JavaScript++

0 TrackBacks

Listed below are links to blogs that reference this entry: Transliterate in JavaScript.

TrackBack URL for this entry: http://blog.versed.se/cgi-bin/mt/mt-tb.cgi/5

Leave a comment

About this Entry

This page contains a single entry by Claes Jakobsson published on July 30, 2008 6:23 PM.

JavaScript, not only for client-side web-fu was the previous entry in this blog.

Find recent content on the main index or look in the archives to find all content.