JavaScript Variable Declaration in JS
Match JavaScript / TypeScript variable declarations (`var`, `let`, `const`), capturing the keyword and identifier name.
Try it in the JS tester →Pattern
regexJS
\b(var|let|const)\s+([a-zA-Z_$][\w$]*)\s*(?:=|;|$) (flags: gm)JavaScript / ECMAScript code
jsJavaScript
const re = new RegExp("\\b(var|let|const)\\s+([a-zA-Z_$][\\w$]*)\\s*(?:=|;|$)", "gm");
const input = "const x = 1;\\nlet name = \"alice\";\\nvar count;";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
How the pattern works
\b(var|let|const) captures the declaration keyword at a word boundary. \s+ requires whitespace. ([a-zA-Z_$][\w$]*) captures a valid JS identifier (starts with letter, underscore, or $). \s*(?:=|;|$) matches the assignment or terminator so we don't mis-match function parameters.
Examples
Input
const x = 1;\nlet name = "alice";\nvar count;Matches
const x =let name =var count;
Input
const { a, b } = objMatches
const { a, b } =
Input
// no declNo match
—