0

I want to parse javascript variable from strings. Something like that,

var string = "<script>window.arr=[1, 2.0, false]</script>";

Is there any way I can get the contents of a single variable from here?

 //something like
 function getVarContent(variable, string){
    var re = new RegExp('');
    return eval(re.exec(string))
}
getVarContent('arr', string)
nikksan
  • 3,341
  • 3
  • 22
  • 27

2 Answers2

1

Maybe overkill for a simple use with a known string, but if you need to support general parsing, you can use the DOMParser if your environment supports it. (See RegEx match open tags except XHTML self-contained tags for reasons why regex may not be the answer)

[insert all the usual caveats about eval()ing strings]

var parser = new DOMParser();
var string = "<script>window.arr=[1, 2.0, false]<\/script>";
var doc = parser.parseFromString(string, "text/html");

var script = doc.querySelector('script')
eval(script.innerHTML)
console.log(window.arr)
Mark
  • 90,562
  • 7
  • 108
  • 148
0

you should put

var string = "<script>window.arr=[1, 2.0, false]</script>";
//only valid letters
var getVar = string.match(/\[[[0-9,.a-z ]+]/g);
console.log(getVar);
var array = JSON.parse(getVar);
console.log(array);
alessandrio
  • 4,282
  • 2
  • 29
  • 40
  • This works the example above, but I need a general solution to be able to get specific variables. – nikksan Nov 12 '17 at 10:56