Search code examples
javascriptfunctionparsingparameters

Get function parameters from a JS function which is a string


I am parsing a webpage and I obtain the following JS function as a string

"translate(737.4170532226562,136.14541625976562)" 

I want to parse the string to obtain the two parameters of the function.

I can parse the string upto the '(' and ',' and ')' to get the arguments - I wanted to know if there is any other method to get the parameters from this string function.


Solution

  • You can use regex for this purpose. For example this one: /([\d\.]+),([\d\.]+)/

    var str = "translate(737.4170532226562,136.14541625976562)";
    var args = /([\d\.]+),([\d\.]+)/.exec(str)
    var a1 = args[1], a2 = args[2];
    
    document.write(['First argument: ', a1, '<br> Second argument: ', a2].join(''))