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


Leave a comment