JavaScript / ECMAScript

Hex Color Code in JS

Match CSS hex color codes in both 3-digit (#RGB) and 6-digit (#RRGGBB) formats.

Try it in the JS tester →

Pattern

regexJS
#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{3})\b   (flags: g)

JavaScript / ECMAScript code

jsJavaScript
const re = new RegExp("#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{3})\\b", "g");
const input = "#ff5733";
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

Matches a # character followed by exactly 6 or exactly 3 hexadecimal digits. The \b word boundary prevents partial matches inside longer strings.

Examples

Input

#ff5733

Matches

  • #ff5733

Input

#abc

Matches

  • #abc

Input

#FFFFFF

Matches

  • #FFFFFF

Same pattern, other engines

← Back to Hex Color Code overview (all engines)