Skip to content

Commit 79e3713

Browse files
committed
Fixed strtr for IE and filter for-in
1 parent a5a443a commit 79e3713

File tree

1 file changed

+37
-18
lines changed

1 file changed

+37
-18
lines changed

functions/strings/strtr.js

Lines changed: 37 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@ function strtr (str, from, to) {
77
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
88
// + input by: Taras Bogach
99
// + bugfixed by: Brett Zamir (http://brett-zamir.me)
10+
// + input by: jpfle
11+
// + bugfixed by: Brett Zamir (http://brett-zamir.me)
1012
// - depends on: krsort
13+
// - depends on: ini_set
1114
// * example 1: $trans = {'hello' : 'hi', 'hi' : 'hello'};
1215
// * example 1: strtr('hi all, I said hello', $trans)
1316
// * returns 1: 'hello all, I said hi'
@@ -22,45 +25,61 @@ function strtr (str, from, to) {
2225
// * example 6: strtr('aa', {'a':1,'aa':2});
2326
// * returns 6: '2'
2427

25-
var fr = '', i = 0, j = 0, lenStr = 0, lenFrom = 0;
28+
var fr = '', i = 0, j = 0, lenStr = 0, lenFrom = 0, tmpStrictForIn = false, fromTypeStr = '', toTypeStr = '', istr = '';
2629
var tmpFrom = [];
27-
var tmpTo = [];
30+
var tmpTo = [];
2831
var ret = '';
2932
var match = false;
3033

3134
// Received replace_pairs?
3235
// Convert to normal from->to chars
3336
if (typeof from === 'object') {
34-
this.krsort(from);
37+
tmpStrictForIn = this.ini_set('phpjs.strictForIn', false); // Not thread-safe; temporarily set to true
38+
from = this.krsort(from);
39+
this.ini_set('phpjs.strictForIn', tmpStrictForIn);
40+
3541
for (fr in from) {
36-
tmpFrom.push(fr);
37-
tmpTo.push(from[fr]);
42+
if (from.hasOwnProperty(fr)) {
43+
tmpFrom.push(fr);
44+
tmpTo.push(from[fr]);
45+
}
3846
}
3947

4048
from = tmpFrom;
41-
to = tmpTo;
49+
to = tmpTo;
4250
}
4351

4452
// Walk through subject and replace chars when needed
4553
lenStr = str.length;
4654
lenFrom = from.length;
55+
fromTypeStr = typeof from === 'string';
56+
toTypeStr = typeof to === 'string';
57+
4758
for (i = 0; i < lenStr; i++) {
4859
match = false;
49-
for (j = 0; j < lenFrom; j++) {
50-
if (str.substr(i, from[j].length) == from[j]) {
51-
match = true;
52-
53-
// Fast forward
54-
i = (i + from[j].length)-1;
55-
56-
break;
60+
if (fromTypeStr) {
61+
istr = str.charAt(i);
62+
for (j = 0; j < lenFrom; j++) {
63+
if (istr == from.charAt(j)) {
64+
match = true;
65+
break;
66+
}
67+
}
68+
}
69+
else {
70+
for (j = 0; j < lenFrom; j++) {
71+
if (str.substr(i, from[j].length) == from[j]) {
72+
match = true;
73+
// Fast forward
74+
i = (i + from[j].length)-1;
75+
break;
76+
}
5777
}
5878
}
59-
60-
if (false !== match) {
61-
ret += to[j];
79+
if (match) {
80+
ret += toTypeStr ? to.charAt(j) : to[j];
6281
} else {
63-
ret += str[i];
82+
ret += str.charAt(i);
6483
}
6584
}
6685

0 commit comments

Comments
 (0)