I would like to get the value of a variable, from a string, using JavaScript.
For example:
var string = "var example1 = 'Hello!'; var example2 = 'Goodbye!'";
string.getValueOfVariable("example1");
...Or something like that. Any suggestions?
You are going to have to evaluate the string. It is not a great idea to evaluate code because it can cause XSS.
function badIdea (code, theVar) {
var x = new Function(`${code}; return ${theVar};`)
return x()
}
var string = "var example1 = 'Hello!'; var example2 = 'Goodbye!'";
console.log(badIdea(string, 'example1'))
console.log(badIdea(string, 'example2'))
eval() is a bad idea? I'm using this for a Chrome Extension, not for my website.You can use eval function:
var string = "var example1 = 'Hello!'; var example2 = 'Goodbye!'";
eval(string);
console.log(example1);
Warning: Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use
eval().