July 2008 Archives

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++

About this Archive

This page is an archive of entries from July 2008 listed from newest to oldest.

May 2008 is the previous archive.

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