How can I replace tokens in string?

Viewed 190
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 ?));
2 Answers

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);

str.replace(/(?<=\$ENV\[)[^\]]+/, match => item[match]);
Related