Replace multiple values in a string based on find / replace pairs
How to replace values as an array by replacing in javascript.
I want to do a number replacement (for example) together. like this?
1
-replace whit-> 11
2
-replace whit->22
DEMO: http://jsfiddle.net/ygxfy/
<script type="text/javascript">
var array = {"1":"11", "2":"22"}
var str="13332";
document.write(str.replace(array));
</script>
+3
source to share
5 answers
You need to create a template using RegEx and then pass it to the method .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];
});
}
+5
source to share
http://jsfiddle.net/mendesjuan/uHUs9/
You can pass a function to replace method
RegExp.escape = function(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
String.prototype.mapReplace = function (replacements) {
var regex = [];
for (var prop in replacements) {
regex.push(RegExp.escape(prop));
}
regex = new RegExp( regex.join('|'), "g" );
return this.replace(regex, function(match){
return map[match];
});
}
var map = {"1":"11", "2":"22"};
var str="13332";
document.write(str.mapReplace(map));
+3
source to share