0

I am trying to capture variable names from the variable declaration. The variables are declared and initialized in the following manner:

let URL="https://www.lipsum.com/", error, pass=true;

I have this above code in the form of a string and I want to obtain the name of the variables using RegEX.

I am using this regex expression: /let\s+([\w_$]+)(?:=.*),?/;

However, I am only getting URL in the output

const str = `let URL="https://www.lipsum.com/", error, pass=true;`;
const regex = /let\s+([\w_$]+)(?:=.*),?/;

console.log(str.match(regex));

How do I obtain the variable names URL, error, and pass from the given string?

1
  • Yeah, A parser is also in my list, but parser like esprima, acorn, etc. have many other things and I have only a single requirement. So using a parser would be too much. Commented Jun 9, 2021 at 12:03

1 Answer 1

3

You can first split it with , and then match it using regex

/(?: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);

EDIT: Some cases were not covered so I come up with one more solution

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);

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks this works, but it fails in one case ie. when we have a comma as a value for a variable or a value contains a comma. For example an array. But Your answers work for most of the cases. Thanks!
I didn't get you, Please tell me so that I can edit the answer as per your requirement...
if str =let URL="https://www.lipsum.com/", error=[true, false], pass=true; Then in this case the output will be URL, error, true, false, pass. But none and false are not variables.
@ShantanuKaushik I've edited the answer. Please check and see if it covers all of your corner cases.
I would be happier if you could come up with more corner cases, It will help me to identify corner cases better next time. Thanks
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.