DEV Community

Taufik Nurrohman
Taufik Nurrohman

Posted on • Updated on

Match Valid HEX/HEX+A Color String using Regular Expression

HEX color normally accept 6 input of 0 to 9 and a to f excluding the hash prefix, and they are case insensitive. I put the important part in a group just in case you want to take it using exec() or match():

let color = /^#([a-f0-9]{6})$/i;
Enter fullscreen mode Exit fullscreen mode

Sometimes, HEX color can be narrowed down into 3 input (e.g. from #aabbcc to #abc):

let color = /^#((?:[a-f0-9]{1,2}){3})$/i;
Enter fullscreen mode Exit fullscreen mode

FYI, current CSS specification allow us to store alpha channel in a HEX color. So #000000, #000, #000000ff and #000f means black. #00000000 and #0000 means transparent:

let color = /^#((?:[a-f0-9]{1,2}){3,4})$/i;
Enter fullscreen mode Exit fullscreen mode

Narrow down the pattern:

let color = /^#((?:[a-f\d]{1,2}){3,4})$/i;
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
lupusinferni315 profile image
Raistlin Wolfe

That last regex returns true for #ABDFF which is not a valid hex color.