JavaScript strtr
Translates characters in str using given translation tables
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 29 3031 32 33 34 3536 37 38 39 4041 42 43 44 4546 47 48 49 5051 52 53 54 5556 57 58 59 6061 62 63 64 6566 67 68 69 7071 72 73 74 7576 77 78 79 8081 82 83 84 8586 87 88 89 9091 92 93 94 9596 | function strtr (str, from, to) { // Translates characters in str using given translation tables // // version: 1109.2015 // discuss at: http://phpjs.org/functions/strtr // + original by: Brett Zamir (http://brett-zamir.me) // + input by: uestla // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: Alan C // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: Taras Bogach // + bugfixed by: Brett Zamir (http://brett-zamir.me) // + input by: jpfle // + bugfixed by: Brett Zamir (http://brett-zamir.me) // - depends on: krsort // - depends on: ini_set // * example 1: $trans = {'hello' : 'hi', 'hi' : 'hello'}; // * example 1: strtr('hi all, I said hello', $trans) // * returns 1: 'hello all, I said hi' // * example 2: strtr('äaabaåccasdeöoo', 'äåö','aao'); // * returns 2: 'aaabaaccasdeooo' // * example 3: strtr('ääääääää', 'ä', 'a'); // * returns 3: 'aaaaaaaa' // * example 4: strtr('http', 'pthxyz','xyzpth'); // * returns 4: 'zyyx' // * example 5: strtr('zyyx', 'pthxyz','xyzpth'); // * returns 5: 'http' // * example 6: strtr('aa', {'a':1,'aa':2}); // * returns 6: '2' var fr = '', i = 0, j = 0, lenStr = 0, lenFrom = 0, tmpStrictForIn = false, fromTypeStr = '', toTypeStr = '', istr = ''; var tmpFrom = []; var tmpTo = []; var ret = ''; var match = false; // Received replace_pairs? // Convert to normal from->to chars if (typeof from === 'object') { tmpStrictForIn = this.ini_set('phpjs.strictForIn', false); // Not thread-safe; temporarily set to true from = this.krsort(from); this.ini_set('phpjs.strictForIn', tmpStrictForIn); for (fr in from) { if (from.hasOwnProperty(fr)) { tmpFrom.push(fr); tmpTo.push(from[fr]); } } from = tmpFrom; to = tmpTo; } // Walk through subject and replace chars when needed lenStr = str.length; lenFrom = from.length; fromTypeStr = typeof from === 'string'; toTypeStr = typeof to === 'string'; for (i = 0; i < lenStr; i++) { match = false; if (fromTypeStr) { istr = str.charAt(i); for (j = 0; j < lenFrom; j++) { if (istr == from.charAt(j)) { match = true; break; } } } else { for (j = 0; j < lenFrom; j++) { if (str.substr(i, from[j].length) == from[j]) { match = true; // Fast forward i = (i + from[j].length) - 1; break; } } } if (match) { ret += toTypeStr ? to.charAt(j) : to[j]; } else { ret += str.charAt(i); } } return ret;} |
Examples
» Example 1
Running
1 2 | $trans = {'hello' : 'hi', 'hi' : 'hello'}; strtr('hi all, I said hello', $trans) |
Should return
1 | 'hello all, I said hi' |
» Example 2
Running
1 | strtr('äaabaåccasdeöoo', 'äåö','aao'); |
Should return
1 | 'aaabaaccasdeooo' |
Dependencies
In order to use this function, you also need:
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have strtr goodness in JavaScript.
@Breton: I can't verify it because I don't have IE9, but my guess on a fix would be changing line 55 from...
tmpFrom.push(fr);
to...
tmpFrom.push('' + fr);
Let us know if this fixes it.
Hi, there is a new bug in IE9 with the function strtr !
This line doesn't work : "if (str.substr(i, from[j].length) == from[j]) {"
Have you got any idea ?
You can see the error here : http://imageshack.us/photo/my-images/805/bugc.jpg/
Fucking IE ! ^^'
Hey i maid even bether one look down:
it contanis 0 loops for norma use and 1 loop for advanced use
function strtr(s,f,t)
{
core=function(str,from,to){//core function
str=str.split(from);//breake parts that we wan't to
str=str.join(to);//glue with new parts that we wan't to
return str;
};//end of core function
if(!t){//check if we use advanced option
r=s;
for(e in f){//loop
r=core(r,e,f[e]);//call our core function
}
return r;// end code and retun value
}
//normal use
return core(s,f,t); // just call normal core function and return
}
/*
example:
normal use:
strtr("This string is string.","string","text");
=This text is text.
advanced use
strtr("This string is texty.",{'texty':'text','string':'text'});
=This text is string.
advanced use WARNING!
strtr("This string is text.",{'text':'string','string':'text'});
=This text is text.
this is not switcher it's replacer!!
*/
What about something more like this? I saw an example of using this for urlencode and thought it would work well for strtr.
function strtr(base, old, n){
return base.replace(/[A-Za-z0-9_.-]/g, function (s) {
for (var k = 0; k < old.length; k++) {
if (s == old.charAt(k) && k < n.length) {
return n.charAt(k);
}
}
});
}
@jpfle: Sorry, I had also needed to update krsort() recently too. Please use the version at http://github.com/kvz/phpjs/blob/master/functions/array/krsort.js
@Brett: Thanks for your answer. However, it no longer works neither on Firefox nor IE. Here's what I packaged on phpjs.org:
- `i18n_loc_get_default()`
- `i18n_loc_set_default()`
- `ini_set()`
- `krsort()`
- `strtr()`
and then I replaced `strtr()` by github's version. With the same code of my previous comment, "ça et là" is output on Firefox and IE without any translation, namely "ça et là". Firefox's Error Console is empty.
@jpfle: Should now be fixed: http://github.com/kvz/phpjs/blob/master/functions/strings/strtr.js . Please note that I've needed to add a new dependency: ini_set(). Also, this will not work with IE5 as is, since I also added for-in filtering for hasOwnProperty (you can remove the check (or alter it to at least make sure from[fr] is a string) if you need to support IE5, but you risk interfering with other libraries that override the Object prototype; otherwise it's best to leave it as is).
Hi. Thanks for this useful function. I use it in a script generating a table of contents for XHTML pages. Each title in a page is transliterated ('à' => 'a', 'é' => 'e', 'î' => 'i', etc.) with strstr() to create an anchor. However, there's a bug with Internet Explorer 6. Take this code:
var texte = 'çà et là';
texte = strtr(texte, {'ç': 'c', 'à': 'a', ' ': '-'});
alert(texte);
Firefox (3.5.5) outputs "ca-et-la", as expected, but IE6 outputs "ca-undefinedundefined-undefineda".
@kevin van
yes I know my function is just for regulars expressions
it wouldn't work with ayyay but I'll update it later
cheer .
@ kwemart: Thanks for sharing. However with your code, only the 3rd example produces the expected output. The other ones fail :(
hi this function is very nice but I propose an other solution , it only work with a regular expression.
function strtr(str,from,to)
{
var patt=str.split(from),str2="";
var l=patt.length,i=1;
while(i<=l-1){str=str.replace(from,to);i+=1;}
return str;
}
@ Roland Hentschel: Thanks for sharing
@ Frank Forte & T.Wild: Cool, let's continue at the page suggested by T.Wild
@Frank Forte
You may want to post your problem over at
http://phpjs.org/functions/htmlspecialchars
rather than here on strtr
I found the following error with the htmlspecialchars() function when doing the following:
el.innerHTML = htmlspecialchars('test 1 < 2 ');
The output (inserted into the element) was
'test 1 < 2'
The htmlspecialchars function does this:
step 1 < turns to <
step 2 < turns to <
This is because the & symbol would be converted AFTER the < character was converted (or any other character for that matter)
I fixed the problem by moving the line:
entities['38'] = '&';
near the top of the html_translation_table() function,
right above the the following line:
if (useTable === 'HTML_ENTITIES') {
This would make sure that the & characters is converted first, then the rest of the charachters would be converted.
-Frank Forte
An implementation for this script:
http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_chr/
function charmap(font) {
document.write("<style>\n*{font-family:"
+font+"; font-size:24pt;}\n</style>\n");
document.write("<table>\n");
for (x=0;x<16;x++) {
document.write("<tr>\n");
for (y=0;y<16;y++) {
document.write("<td>"+chr(16*x+y)+"</td>\n");
}
document.write("</tr>\n");
}
document.write("</table>\n");
}
There is a bug for the function. For example, when using PHP strtr("abc","abc","cba") the result is "cba". But using this function, the result is "aba". Because the first character "a" is replaced by "c", however it became "a" when trying to replace all character "c" with "a". Maybe here we can use some array to store the status as well the chars in order to solve the problem.
Good Luck


اخبار السيارات
Apr 10th