Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript code regex replace(//g, d["$1"]) does not work as expected

let data = {"phase": 32};
let title = "Phase {phase}";
consolo.log(title.replace(/\{([^\}]+)\}/g, data["$1"]));

Expected: Phase 32

Got: Phase undefined

What’s wrong with this code?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Expected: Phase 32

>Solution :

$ placeholders are interpreted by replace when you pass it a string as a replacement. It’s not a magical syntax-level construct that can apply the same special meaning to an expression like data["$1"]; just like any other function, the argument data["$1"] gets evaluated and only then does the result (undefined) get passed to replace.

However, in addition to a string with $ placeholders, replace also supports a replacement function. You’ll need to use that instead:

let data = {"phase": 32};
let title = "Phase {phase}";
console.log(title.replace(/\{([^\}]+)\}/g, (_, key) => data[key]));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading