Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Regex:查找函数的第一个参数上使用的属性_Javascript_Regex - Fatal编程技术网

Javascript Regex:查找函数的第一个参数上使用的属性

Javascript Regex:查找函数的第一个参数上使用的属性,javascript,regex,Javascript,Regex,在我的代码中,我需要正则表达式在所有这些函数字符串情况下查找第一个参数的动态键: x => x.id // should return 'id' x => x.a.biggerThan(5) // should return 'a' x=>x.b.biggerThan(5) // should return 'b' test => test.c.biggerThan(5) // should return 'c' (x, y) => x.d.biggerTh

在我的代码中,我需要正则表达式在所有这些函数字符串情况下查找第一个参数的动态键:

x => x.id // should return 'id'

x => x.a.biggerThan(5) // should return 'a'

x=>x.b.biggerThan(5) // should return 'b'

test => test.c.biggerThan(5) // should return 'c'

(x, y) => x.d.biggerThan(5) // should return 'd'

x => { return x.e.biggerThan(5); } // should return 'e'

(x, y) => { y = test.description; return x.f.biggerThan(y); } // should return 'f'

function (x) { return x.g.biggerThan(5); } // should return 'g'

function test(x) { return x.h.biggerThan(5); } // should return 'h'

function(x) { return x.i.biggerThan(5); } // should return 'i'

function(x){ return x.j.biggerThan(5); } // should return 'j'

function (x, y) { return x.l.biggerThan(5); } // should return 'l'
--解释我为什么需要它--

这些是用
toString()
方法字符串化的函数,我需要创建一个动态对象,该对象具有要插入该函数的键,如下所示:

// get the key used by the function
const key = getkeyInFunc(func.toString());

// construct a dynamic object using that key
const builder = {
  [key]: {
    biggerThan: // biggerThan function
    // others methods
  }
};

// call the function with the dynamic key as parameter
const result = func(builder);

请帮帮我,因为我对regex=(

我认为这应该可以解决问题:

var result=/return\w+。([a-z]+)./.exec((函数(x){return x.id.something();}).toString())

结果[1];//id


斜杠开始正则表达式时,an尝试匹配字符串中“return”关键字后跟字符(\w)和点的部分,并用“()”组合所需的键。

对于本例,它将起作用

“functionString”.match(/(return |=>)[a-zA-Z_0-9]+?。([a-zA-Z_0-9]+)/)[2]

例如:


“(x,y)=>{y=test.description;return x.f.biggerTha_n(y);}.match(/(return|=>)[a-zA-Z_0-9]+?\([a-zA-Z_0-9]+)/)[2]

但是
id
键始终是
id
?抱歉……不是。这是任何可能的js属性键。对我来说,这似乎是一个。我强烈建议你解释你实际试图做什么,或者提供一些关于你试图解决的问题的上下文。我编辑了更多信息。请检查现在是否清楚我不这么做考虑到您的示例案例,我理解您的问题:如果您有一个字符串
函数测试(x){return x.h.biggerThan(5);}
,您希望它如何匹配
a
?感谢您的回答,当函数为es5格式且带有
return
关键字时,它会工作,但不会与es6 arrow函数匹配。我需要匹配所有这些类型,因为它将用于每个es6和es5 javascript代码。太棒了!它工作了!我只需要插入
`在
`之前和
之后加上
=>
的空格,以匹配第三种情况,这是一个没有空格的箭头函数。非常感谢!
\
之前
这是所有情况的匹配方式:
/(return*|=>*?)[a-zA-Z\u 0-9]+?\([a-zA-Z\u 0-9]+)/