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