我不太确定如何简短地解释这一点,所以标题可能有点令人困惑......
我有这段 JavaScript 代码字符串:(已从换行符、双空格等中删除干净):
function (a, b) { this.super('__construct', a, b); return { foo: this.test, bar: this.ParentFunctionAdd }; }
我试图弄清楚如何从该函数的 return 语句中获取键/值数组。执行代码或使用 eval 不是一个选项。
所以本质上,我想匹配 return 语句的大括号之间的任何内容并获得一个键/值数组作为返回。
期望的结果如下:
{
'foo' : 'this.test',
'bar' : 'this.ParentFunctionAdd'
}
提前致谢!!
最佳答案
如果您更喜欢使用正则表达式,这里有一个解决方案
/([^{,]+):([^},]+)/g
<小时/>
"function (a, b) { this.super('__construct', a, b); return { foo: this.test, bar: this.ParentFunctionAdd }; }".match(/([^{,]+):([^},]+)/g);
这是输出
[" foo: this.test", " bar: this.ParentFunctionAdd "]
如您所见,使用时需要 trim ()值。
检查Demo
关于javascript - 使用正则表达式从 javascript 函数返回语句中查找键/值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24712009/