Qaynaq LABS · TOOLS

REGEX · JAVASCRIPT

Regex explained

^[a-zA-Z_][a-zA-Z0-9_]*$

Matches strings that start with a letter or underscore, followed by zero or more letters, digits, or underscores. Ensures valid identifier-like strings.

Token-by-token breakdown

TokenMeaningExample
^ Anchor: asserts position at start of the string Start of 'abc123'
[ Start of a character class N/A
a-z Range: lowercase letters a through z a, b, ..., z
A-Z Range: uppercase letters A through Z A, B, ..., Z
_ Literal underscore character _
] End of the character class N/A
[ Start of a second character class N/A
a-z Range: lowercase letters a through z a, b, ..., z
A-Z Range: uppercase letters A through Z A, B, ..., Z
0-9 Range: digits 0 through 9 0, 1, ..., 9
_ Literal underscore character _
] End of the character class N/A
* Quantifier: zero or more of the preceding element (the character class) No characters, 'a', '1_', etc.
$ Anchor: asserts position at end of the string End of 'abc123'

Matches

  • a
  • A
  • _
  • abc
  • ABC_123
  • var_name
  • x
  • hello_world123

Does not match

  • 1abc
  • abc!
  • abc def
  • abc@123
  • 123
  • a b
  • a-b

Common pitfalls

  • Forgetting the ^ anchor may allow leading digits or other invalid characters.
  • Assuming this matches all valid JavaScript identifiers (e.g., fails for Unicode identifiers like 'é' or '$').
  • Overlooking that * allows zero occurrences, so empty string matches if not for ^ and $ anchors.
  • Confusing with regexes that allow hyphens or other special characters in identifiers.

Performance notes

No catastrophic backtracking risk due to simple quantifiers and character classes. Efficient for typical use cases. Anchors ensure linear scanning.

About regular expressions

Regular expressions are tiny programs that match patterns in text. They're powerful and notoriously cryptic — most engineers can write them but few can read them confidently. Qaynaq Labs' regex explainer breaks any pattern into its constituent tokens, shows what each one does, and runs through both matching and non-matching examples so you can verify the logic.

Different regex flavors (JavaScript, PCRE, Python, Go) have subtle differences in syntax and supported features. Pick your flavor in the input — the explainer accounts for it.

Frequently asked

Does this match all valid JavaScript identifiers?

No. JavaScript identifiers can include Unicode letters (e.g., 'é', 'α'), $, and other characters not covered by [a-zA-Z0-9_].

Why is the * quantifier used instead of +?

The * allows zero or more characters after the first, so it matches single-character identifiers like 'a' or '_'. Using + would require at least one additional character.

Can this regex match reserved keywords like 'function' or 'var'?

Yes, it matches any string composed of letters, digits, and underscores, regardless of whether it is a reserved keyword.