Skip to content
Advertisement

Is it possible to interpolate Javascript regex match in a string template?

For example… (this fails)

const currencyMap = {
  "$": "USD",
  "€": "EUR",
};

const r = '$100'.replace(/($)([0-9]*)/g, `${currencyMap[$1]}$2`);
console.log(r);

Is there a way to make this sort of thing work? $1 is available when it’s used in a string, but not as a key.

Advertisement

Answer

Unfortunately no, you’ll have to use a replacer function instead:

const currencyMap = {
    "$": "USD",
    "€": "EUR",
};

const r = '$100'.replace(/($)(d*)/g, (_, $1, $2) => currencyMap[$1] + $2);
console.log(r);

Also note that you can use d instead of [0-9] instead, it makes the regex a bit nicer to read.

If you don’t actually need the second group for something special, you can just echo back the match in the object:

const currencyMap = {
    "$": "USD",
    "€": "EUR",
};

const r = '$100'.replace(/[$€]/g, match => currencyMap[match]);
console.log(r);
Advertisement