I\'ve been trying to figure out how to map a set of characters in a string to another set similar to the tr
function in Perl.
I found this site that sh
Method:
String.prototype.mapReplace = function(map) {
var regex = [];
for(var key in map)
regex.push(key.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"));
return this.replace(new RegExp(regex.join('|'),"g"),function(word){
return map[word];
});
};
A perfect example:
var s = "I think Peak rocks!"
s.mapReplace({"I think":"Actually","rocks":"sucks"})
// console: "Actually Peak sucks!"