JavaScript Variable Declaration in GO
Match JavaScript / TypeScript variable declarations (`var`, `let`, `const`), capturing the keyword and identifier name.
Try it in the GO tester →Pattern
regexGO
\b(var|let|const)\s+([a-zA-Z_$][\w$]*)\s*(?:=|;|$) (flags: gm)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(?m)\b(var|let|const)\s+([a-zA-Z_$][\w$]*)\s*(?:=|;|$)`)
input := `const x = 1;\nlet name = "alice";\nvar count;`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
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
—