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.