WORKED EXAMPLE / ECMASCRIPT

CSS hex color regex

A CSS-oriented hex color check accepting 3-, 6-, or 8-digit notation with an optional leading #.

Pattern

^#?(?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$
Flavor
JavaScript (ECMAScript)
Flags
Flags: i

What it does

The alternatives cover shorthand RGB, full RGB, and full RGBA values. Case-insensitive matching permits the A–F digits in either case while anchors reject extra text.

Token-by-token explanation

  1. ^

    Starts matching at the beginning of the color value.

  2. #?

    Allows one optional leading hash character.

  3. (?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})

    Requires exactly 3 RGB shorthand digits, 6 full RGB digits, or 8 full RGBA digits.

  4. $

    Stops matching at the end of the color value.

Test strings

Matches

  • #0f8
  • 336699
  • #112233cc

Does not match

  • #12
  • #xyz

Common mistakes

  • Allowing any three, six, or eight characters instead of limiting each digit to 0–9 and A–F.
  • Assuming an eight-digit hex color uses ARGB order when CSS defines it as RRGGBBAA.

Limitations

  • This covers selected hexadecimal CSS forms only; it does not accept 4-digit #RGBA shorthand or other valid CSS color syntaxes such as rgb(), hsl(), named colors, or color().