1 回答

TA贡献1818条经验 获得超3个赞
尝试使用正则表达式模式(\w+)=(.*?)(?:,\s*(?=\w+=)|$),然后捕获所有匹配项:
var input = "a=func(1, 2, 2), b='hey', c=foobar('text'), d=1";
var regex = /(\w+)=(.*?)(?:,\s*(?=\w+=)|$)/g;
var match = regex.exec(input);
var result = [];
while (match != null) {
result.push(new Array(match[1], match[2]));
match = regex.exec(input);
}
console.log(result);
这是模式的作用:
(\w+) match AND capture a key
= match an =
(.*?) then match AND capture anything, until we see
(?:,\s*(?=\w+=)|$) a comma, followed by optional space, and the next key
OR the end of the input string
然后,我们使用第一个捕获组作为键,第二个捕获组作为值来构建您预期的二维数组。
添加回答
举报