Alex Rivera | Logout

Parsing Javascript using Ruby code

Asked 2011-02-09T00:29:15.753
10

I'm writing a test code in Ruby and trying to parse a HTML source file of a website. It has a JavaScript variable which I can use to compare it against other values. For example:

<script type="text/javascript" language="JavaScript">
  function GetParam(name) {   
    var req_var = {
      a: 'xyz', 
      b: 'yy.com', 
      c: 'en', 
      d:0, 
      e: 'y'
     };
  }
</script>

Here I want to extract the variable req_var from this function. Is it possible to do that? If so can anyone please help me with that?

Edit
Report

2 Answers

9

javascript parser in ruby

answered 2011-02-09T00:35:21.583
4

You could use a regular expression to parse it out like this:

k = "function GetParam(name) { var req_var = { a: 'xyz' , b: 'yy.com' , c: 'en' , d:0 , e: 'y'}; }"
variable = k.match(/var\s+req_var\s+=\s+(.*?);/m)[1]
p variable

=> "{ a: 'xyz' , b: 'yy.com' , c: 'en' , d:0 , e: 'y'}"
answered 2011-02-09T00:37:41.017

Your Answer