2

I have the following snippet from this post, this code replaces the token $ENV[accountsDomain] in a string with the key from item object accountsDomain: 'www.yahoo.com' and similarly for accountsUrl

how can I run replace conditionally, replace the string only if item[g1] exists, as these keys are optional

const item = {
  accountsUrl: 'www.google.com',
  accountsDomain: 'www.yahoo.com'
}
const regex = /\$ENV\[(\w+)]/
let s = "foo$ENV[accountsDomain]bar";
s = s.replace(regex, (m, g1) => item[g1] || m);
console.log(s);
dota2pro
  • 7,220
  • 7
  • 44
  • 79

1 Answers1

0

You cannot do that in replace, you have to do it outside.

const item = {
  accountsUrl: 'www.google.com',
  accountsDomain: 'www.yahoo.com'
}

function replaceItem(item, key) {
  const regex = /\$ENV\[(\w+)]/
  let s = `foo$ENV[${key}]bar`;
  let [, match] = s.match(regex);
  return item[match] && s.replace(regex, (m, g1) => item[g1]);
}

console.log('result with existing key:', replaceItem(item, 'accountsDomain'))
console.log('result with un-existing key:', replaceItem(item, 'accDomain'))
EugenSunic
  • 13,162
  • 13
  • 64
  • 86