简体   繁体   English

正则表达式从字符串中获取所有 JavaScript 变量名称和值

[英]regex to get all JavaScript variable names and values from string

say I have the following string:说我有以下字符串:

let code = `
      var x = 4;
      var y=9,
          w=8
      var z=8080
      other()
      x=12

`

How do I write a regex that gets all of the variable declarations?如何编写一个获取所有变量声明的正则表达式? In this case, I want to return all statements, and no expressions, so exclude the other() and x=12 part.在这种情况下,我想返回所有语句,而不是表达式,所以排除other()x=12部分。 So far I have到目前为止我有

 let results = ` var x = 4; var y=9, w=8 var z=8080 other() x=12 `.match(/(var)(.*?)(;|,|\n)/g); console.log(results);

But I couldn't figure out how to include the w=8 part also, since that's also a declaration statement, while excluding the expressions.但我不知道如何包含 w=8 部分,因为这也是一个声明语句,同时排除了表达式。 I tried .match(/(var|\n)(.*?)(;|,|\n)/g) but that also returns x=12, which I don't want.我试过.match(/(var|\n)(.*?)(;|,|\n)/g)但这也返回 x=12,这是我不想要的。 I need to also return all statement blocks even if there is a comma right before it (either on a previous line, or previous character, anything that would normally allow a variable declaration).我还需要返回所有语句块,即使它前面有一个逗号(在前一行或前一个字符上,任何通常允许变量声明的东西)。

Any idea how to do this with regex?知道如何用正则表达式做到这一点吗?

EDIT:编辑:

with uglifyjs I'm able to do the following (which is the result I want):使用 uglifyjs 我可以执行以下操作(这是我想要的结果):

 let strin = ` var x = 4; var y=9, w=8, kk = { ok:1234 }, p, a = undefined var z=8080 other() x=12 ` let results = UglifyJS.parse(strin).body.filter(x=>x.__proto__.TYPE == "Var").map(x=> x.definitions.map(y=>({ name:y.name.name, value:y.value? findInPos(y.value.start, y.value.end,strin): undefined })), ).flat() function findInPos(start, end,str) { return str.substring( start.pos, end.endpos ); }
 <script type="text/javascript" src="https://yaakovyitzchak.github.io/coby/uglify.js"> </script>

But it seems a bit overkill just to extract the string value of each variable?但是仅仅提取每个变量的字符串值似乎有点过头了? (I don't need to evaluate it, just get the string value like so) (我不需要评估它,只需像这样获取字符串值)

The task can be nicely solved with TypeScript Compiler API, as it can parse not only TypeScript but JavaScript code too. The task can be nicely solved with TypeScript Compiler API, as it can parse not only TypeScript but JavaScript code too. Since TypeScript compiles into JavaScript - there should be no problem to integrate the following TS snippet into a JS project.由于 TypeScript 编译为 JavaScript - 将以下 TS 片段集成到 JS 项目中应该没有问题。

See demo查看演示

import ts from "typescript";

const code = `
    var x = 4;
    var y=9,
        w=8
    var z=8080
    other()
    x=12
`;

const sf = ts.createSourceFile(
    "test.js",
    code,
    ts.ScriptTarget.ES2017,
    true,
    ts.ScriptKind.JS,
);

sf.forEachChild((n) => {
    if (ts.isVariableStatement(n)) {
        n.declarationList.declarations.forEach((decl) => {
            const name = decl.name.getText();
            const value = decl.initializer?.getText();
            console.log(`${name} = ${value}`);
        });
    }
});

The code above prints the following output to console:上面的代码将以下 output 打印到控制台:

x = 4
y = 9
w = 8
z = 8080

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM