-1

I'm trying to write a regular expression for use with matchAll to match all const and let variable declarations and their usages.

Examples:

const foo = (x) => x
const bar = 'bar'; let baz = 123, qux = 456
                                   , quux = 1 / 2

foo(bar)
baz = qux

It should really work with any valid JavaScript. So far I've come up with the following:

str.matchAll(/\b(?:const|let)\b\s+(\w+)/g)

which produces what I want:

[
  ["const foo", "foo"],
  ["const bar", "bar"],
  ["let baz", "baz"]
]

except that it misses the comma-delimited declarations. I imagine they'd appear in the last array as ["let baz", "baz", "qux", "quux"], although the structure isn't critical as long as everything is there. I've tried tacking something like (?:\s*=.*,\s*(\w+))*? onto the end of the regex but no luck. Regular expressions aren't my strong point. :/

The ultimate goal is to replace all of the matches with object property assignments, i.e. const foo = bar will become PREFIX.foo = PREFIX.bar.

I'm sure it's possible to do this with an AST library as well, but this is for a small NPM package and I'd rather keep it small if possible.

apostl3pol
  • 760
  • 6
  • 15
  • Frustrating that this was closed and downvoted. The referenced “duplicate” question is not what I was asking, and I think I was pretty clear. Its only relevant answer suggests using an AST, which I clearly stated that I’d rather not do if possible. – apostl3pol May 21 '22 at 17:56

0 Answers0