Reputation: 25840
Is there a simplified way in JavaScript + Reg-Ex to replace all occurrences of each symbol in a set with its alternative symbol?
Example:
"Test: 1, 2, 3 and 1".replace("123", "ABC");
// we need to get: "Test: A, B, C and A";
I mean, is there any Reg-Ex trick to avoid a for-loop here? And anyway, what would be the most efficient way to do it?
Provisions:
Upvotes: 0
Views: 160
Reputation: 70732
You could build out your replacements using an Object Literal.
var map = {'1':'A', '2':'B', '3':'C'};
str = str.replace(/[123]/g, function(k) {
return map[k];
});
Or create a custom function using a map for this:
function _replace(str, map) {
var re = new RegExp('['+Object.keys(map).join('')+']','g');
return str.replace(re, function(x) { return map[x] });
}
Upvotes: 4