The reason your code doesn't work is because window['__' + "$1"]
is evaluated first, so:
sentence.replace(/__(\w+)/gs,window['__' + "$1"]);
...becomes:
sentence.replace(/__(\w+)/gs, window['__$1']);
As window['__$1']
doesn't exist on the window object, this results in undefined
, so you get:
sentence.replace(/__(\w+)/gs, undefined);
This is what causes you to get undefined
in your result. Instead, you can use the replacement function of .replace()
to grab the group from the second argument and then use it for the replacement value returned by the callback:
var __total = 8;
var sentence = "There are __total planets in the solar system";
const res = sentence.replace(/__(\w+)/gs, (_, g) => window['__' + g]);
console.log(res);
However, accessing global variables on the window like this isn't the best idea as this won't work for local variables or variables declared with let
or const
. I suggest you create your own object which you can then access like so:
const obj = {
__total: 8,
};
const sentence = "There are __total planets in the solar system";
const res = sentence.replace(/__(\w+)/gs, (_, g) => obj['__' + g]);
console.log(res);