使用正则表达式从javascript函数返回语句中查找键/值

Using regex to find key/values from a javascript function return statement

本文关键字:查找 语句 返回 正则表达式 javascript 函数      更新时间:2023-09-26

我不太确定如何简短地解释这一点,所以标题可能有点令人困惑…

我有这段javascript代码string:(从换行符,双空格等中剥离干净):

function (a, b) { this.super('__construct', a, b); return { foo: this.test, bar: this.ParentFunctionAdd }; } 

我想弄清楚如何从这个函数的返回语句中得到一个键/值数组。执行代码或使用eval不是一个选项。

本质上,我想要匹配return语句的大括号之间的任何内容,并在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 "]

正如您所看到的,您需要在使用()值时修剪它们。

检查演示