我试图从变量声明中捕获变量名称。变量的声明和初始化方式如下:
let URL="https://www.lipsum.com/", error, pass=true;
我有上面的字符串形式的代码,我想使用 RegEX 获取变量的名称。
我正在使用这个正则表达式: /let\s+([\w_$]+)(?:=.*),?/;
但是,我只进入URL
输出
const str = `let URL="https://www.lipsum.com/", error, pass=true;`;
const regex = /let\s+([\w_$]+)(?:=.*),?/;
console.log(str.match(regex));
如何获取变量名URL
,error
以及pass
从给定的字符串?
您可以先将其拆分,
,然后使用正则表达式进行匹配
/(?:let)?\s*(\w+)(=.*)?/
const str = `let URL="https://www.lipsum.com/", error, pass=true;`;
const matches = str.split(",").map((s) => {
const match = s.match(/(?:let)?\s*(\w+)(=.*)?/);
return match[1];
});
console.log(matches);
编辑:有些情况没有涵盖,所以我想出了另一种解决方案
const str = `let abc123 , two, three,
URL="https://www.lipsum.com/",
log,
error=[true, false],
pass=true,
obj={name: "test", nestedOBj: {a: 20}},
obj2 = [{}]
`;
const matches = str.split(",").flatMap((s) => {
let match;
if (s.includes("=")) {
match = s.match(/(\w+)\s*(?=\=)/i);
return match[1];
} else if (!s.match(/[\[\]\{\}]/)) {
return s.match(/(?:(?:let|const|var)\s+)?(\w+)/)[1];
} else return [];
});
console.log(matches);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句