从字符串的 JS 函数中获取函数参数

Get function parameters from a JS function which is a string

本文关键字:函数 参数 获取 JS 字符串      更新时间:2023-09-26

我正在解析一个网页,我以字符串形式获得以下JS函数

"translate(737.4170532226562,136.14541625976562)" 

我想解析字符串以获取函数的两个参数。

我可以将字符串解析为"("和","和")"以获取参数 - 我想知道是否有任何其他方法可以从这个字符串函数中获取参数。

您可以使用正则表达式来实现此目的。例如这个:/(['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(''))

这可能是矫枉过正。但是我很无聊。所以这里有一个函数名称解析器。它获取函数名称和参数。

var program = "translate(737.4170532226562,136.14541625976562)";
function Parser(s)
{
  this.text = s;
  this.length = s.length;
  this.position = 0;
  this.look = '0'
  this.next();
}
Parser.prototype.isName = function() {
    return this.look <= 'z' && this.look >= 'a' || this.look <= '9' && this.look >= '0' || this.look == '.'    
}
Parser.prototype.next = function() {
    this.look = this.text[this.position++];
}
Parser.prototype.getName = function() {
  var name = "";
  while(parser.isName()) {
    name += parser.look;
    parser.next();
  }
  return name;
}
var parser = new Parser(program);
var fname = parser.getName();
var args = [];
if(parser.look == '(') {
  parser.next();
    args.push(parser.getName());
    while(parser.look == ',') {
        parser.next();
        args.push(parser.getName());
    }
} else {
    throw new Error("name must be followed by ()")
}
console.log(fname, args);