Sunday, May 18, 2008

(str)tr for JavaScript

I couldn't find a function resembling Ruby's tr or PHP's strtr in JavaScript, so I created one. Here's the code:

function tr(str, from, to) {
var subst;
for (i = 0; i < from.length; i++) {
subst = (to[i]) ? to[i] : to[to.length-1];
str = str.replace(new RegExp(str[str.indexOf(from[i])], 'g'), subst);
return str;


moussor said...

I couldn't find one either until I found yours.

Well done, cheers =)

Jani Hartikainen said...


This script doesn't seem to work in IE or Safari. However, I modified it a bit and this seems to work:

function tr(str, from, to) {
for(var i = 0; i < from.length; i++) {
str = str.replace(new RegExp(from.charAt(i),'g'), to.charAt(i));

return str;

The problem seems to be that IE does not support foo[i] notation with strings

Colin said...

This won't work. Try doing:

alert(tr('abcde', 'abcde','bcdef'));

In this case, "a" is converted to "b". But then both "b"s are converted to "c"s, etc.. You'll end up with "fffff".

ntoniazzi said...

Something easier that doesn't involve regular expressions :

function tr (str, from, to) {
var out = "", i, m, p, ;
for (i = 0, m = s.length; i < m; i++) {
p = from.indexOf(str.charAt(i));
if (p >= 0) {
out = out + to.charAt(p);
else {
out += str.charAt(i);
return out;