RegExを使用してパターンを作成し、それを.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];
});
}