JavaScript theorytheory 0/50 · 0%
Strings · medium

35. Regular expressions

Validating input without writing a parser.

Regexes match patterns. Anchors `^`/`$` bound the whole string, character classes and quantifiers describe shape, and flags such as `i` and `g` change behaviour.

const isAddress = /^0x[a-fA-F0-9]{40}$/;
isAddress.test(input);

Beware the `g` flag with `test`: it keeps `lastIndex` state between calls. Keep patterns simple and readable.

Check your understanding

  1. 1. What does `^...$` enforce?

  2. 2. How many hex characters follow 0x in an address?

  3. 3. What is the `g` flag pitfall with `test`?