你必須創建一個模式,使用正則表達式,然後將其傳遞給.replace
方法。
var array = {"1":"11", "2":"22"}; // <-- Not an array btw.
// Output. Example: "1133322"
document.write(special_replace("13332", array));
function special_replace(string_input, obj_replace_dictionary) {
// Construct a RegEx from the dictionary
var pattern = [];
for (var name in obj_replace_dictionary) {
if (obj_replace_dictionary.hasOwnProperty(name)) {
// Escape characters
pattern.push(name.replace(/([[^$.|?*+(){}\\])/g, '\\$1'));
}
}
// Concatenate keys, and create a Regular expression:
pattern = new RegExp(pattern.join('|'), 'g');
// Call String.replace with a regex, and function argument.
return string_input.replace(pattern, function(match) {
return obj_replace_dictionary[match];
});
}
但是沒有數組...... – xdazz 2012-04-06 14:51:02
這不是一個數組,它是一個名爲「數組」的引用對象的變量。還要注意,它只是不適合使用'document.write()'。 – Phrogz 2012-04-06 14:51:46