【问题标题】:Get function parameters from a JS function which is a string从一个字符串的 JS 函数中获取函数参数
【发布时间】:2016-04-27 22:59:59
【问题描述】:

我正在解析一个网页,我得到以下 JS 函数作为字符串

"translate(737.4170532226562,136.14541625976562)" 

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

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

【问题讨论】:

  • 这在语法中被称为产生式,所以希望这就是你每次解析时的样子。
  • 使用像/translate\(([0-9\.]+),([0-9\.])\)/这样的正则表达式。或者你可以创建一个translate(a,b) 函数和eval 字符串,当然,如果你相信来源的话。
  • 嘿@Dinesh 看看我的回答,让我知道你的想法。

标签: javascript function parsing parameters


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    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);
    

    【讨论】:

    • 感谢您的及时答复。我想知道我们是否可以有一个更小更紧凑的解决方案。
    • 看看 angular 源代码,看看他们的正则表达式来提取变量名,但乞丐不应该是选择者:)
    猜你喜欢
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 2021-11-23
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 2015-08-17
    相关资源
    最近更新 更多