vitaly-t
vitaly-t

Reputation: 25840

Replace individual symbols in a set

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:

  1. In my task the set of symbols is usually very short (could even be 3 symbols) and it is static, not dynamic, very similar to the example shown.
  2. Sometimes a symbol needs to be replaced with an empty '', i.e. removed.

Upvotes: 0

Views: 160

Answers (1)

hwnd
hwnd

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

Related Questions