0

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?

1 Answer 1

1

You need to use a function for this:

console.log('<<obj.aa>>'.replace(/<<obj\.(.*)>>/, (_,prop) => obj[prop]));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.