The following code tries (in a single replace call) to substitute an object element string notation with an object element value using regexp replace.
But only errors are observed in this approach (refer logs below).
The sample code tries to replace the string <> with the object element obj.aa
var obj = {};
obj.aa = '1';
obj.bb = '21';
console.log('<<obj.aa>>'.replace(/<<obj\.(.*)>>/,obj['$1']));
console.log('<<obj.aa>>'.replace(/<<obj\.(.*)>>/,`obj[$1]`));
console.log('<<obj.aa>>'.replace(/<<obj\.(.*)>>/,`${obj[$1]}`));
Log is shown below:
undefined
obj[aa]
console.log('<<obj.aa>>'.replace(/<<obj\.(.*)>>/,`${obj[$1]}`));
^
ReferenceError: $1 is not defined
at Object.<anonymous> (source_file.js:6:57)
at Module._compile (module.js:410:26)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:442:10)
at startup (node.js:136:18)
at node.js:966:3
Is there any workaround / correct way to achieve this in a replace call line?