简体   繁体   中英

How can I replace tokens in string?

I have a json object

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

and an input string foo$ENV[accountsDomain]bar . I want to replace the $ENV[accountsDomain] with item.accountsDomain 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 ?));

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM