0

I have some variables that was created dynamically. All of the variables using double underscores ('__') as a prefix. So What I want to do is replace any characters in a sentence that contain double underscores prefix with the variables. Here is an example:

input

var __total = 8;
var sentence = "There are __total planets in the solar system";

expected result

There are 8 planets in the solar system

Here is my regex to parse the string, but it return undefined:

sentence.replace(/__(\w+)/gs,window['__' + "$1"]);
Kevin A.S.
  • 123
  • 7

3 Answers3

2

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);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
1

You can use eval() here an example:

let __total = 8;

let str = "There are __total planets in the solar system ";
let regex = /__(\w+)/g;
let variables = str.match(regex);
console.log(`There are ${eval(variables[0])} planets in the solar system`)

let __total = 8;

let str = "There are __total planets in the solar system ";
let regex = /__(\w+)/g;
let variables = str.match(regex);

console.log(`There are ${eval(variables[0])} planets in the solar system`)
Pouya Ak
  • 171
  • 1
  • 10
0

you have to split the sentence and use the varialbe to get the value assigned to that.

So you have to use '+' sign for spliting and adding to the sentence

So you just find that word using regex. Suppose you store it in the variable called myVar. Then you can use the following code: sentence.replace(myVar,'+ myVar +');

So your end goal to be to make your sentence like:

sentence = "There are "+__total+" planets in the solar system";
Minal Shah
  • 1,402
  • 1
  • 5
  • 13