你必须创建一个模式,使用正则表达式,然后将其传递给.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