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)
2
  • Do you trust the contents of those strings? Would it be feasible to just execute it? Commented Nov 11, 2017 at 14:38
  • No, I dont want to execute all of it.Simply get parts of it. Commented Nov 12, 2017 at 10:55

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

I really dont want to execute the whole script.
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);

1 Comment

This works the example above, but I need a general solution to be able to get specific variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.