javascript - 正则表达式:查找函数第一个参数使用的属性

标签 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.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);

请帮助我,因为我对正则表达式很糟糕=(

最佳答案

对于这个例子,它会起作用

"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]

关于javascript - 正则表达式:查找函数第一个参数使用的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58242384/

相关文章:

javascript - jQuery通过脚本标签加载正常工作,但无法在Wordpress functions.php中工作

c# - Visual Studio 正则表达式替换重复捕获组

regex - Perl 正则表达式/(\r\n|\r|\n)/

javascript - 附加到字符串 Ramda.js 的末尾

javascript - jQuery 调整大小(),滚动(): good practice to use variables?

regex - 使用正则表达式和通配符查询任意数据

python - 如何在 Python 正则表达式中验证 unicode "word characters"?

c# - 为什么输入字符串 "**$&"上的替换模式 "$1.30"返回一个前面有 "**"且输入字符串为 "after"的字符串?

javascript - 我可以动态地从 javascript 分配一个 Action 吗?

javascript - 使用 moment.js 或使用 JQuery/Javascript 以英文和日文显示日期