2
I have a json object

    const item = {
fooUrl : 'www.google.com',
fooDomain : 'www.yahoo.com'
}

and an input string foo$ENV[fooDomain]bar. I want to replace the $ENV[fooDomain] with item.fooDomain and similarly for accountsUrl, I want this to happen dynamically meaning even if a new unknown key is added the pattern should find and replace $ENV[something] value.

What I have done till now

console.log(str.replace(/(?:^|\s)$ENV[(\w*)](.*?)(?:\s|$)/g,item.accountsUrl // how to make this dynamic ?));
dota2pro
  • 7,220
  • 7
  • 44
  • 79
  • use a callback as an argument: `replace(...., ($0, $1) => items[$1]` – georg Apr 05 '21 at 12:52
  • `str.replace(/\$ENV\[([^\][]*)]/g, (m,x) => item[x] || m)`? Why do you use whitespace boundaries `(?:^|\s)` and `(?:\s|$)` if your string with an expected match has no whitespace on both ends of the match? – Wiktor Stribiżew Apr 05 '21 at 12:53

2 Answers2

3

You can just use a match and a single capture group to get the property name that corresponds with the object.

Note that you have to escape the dollar sign and the openings square bracket.

As @Wiktor Stribiżew points out in the comments, you can use || m to return the match in case the group 1 value can not be found in the object.

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);
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0
str.replace(/(?<=\$ENV\[)[^\]]+/, match => item[match]);
MikeM
  • 13,156
  • 2
  • 34
  • 47