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;
}
4 comments:
I couldn't find one either until I found yours.
Well done, cheers =)
Hi
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
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".
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;
}
Post a Comment