How to check if a string is a valid hex color representation? How to check if a string is a valid hex color representation? javascript javascript

How to check if a string is a valid hex color representation?


/^#[0-9A-F]{6}$/i.test('#AABBCC')

To elaborate:

^ -> match beginning
# -> a hash
[0-9A-F] -> any integer from 0 to 9 and any letter from A to F
{6} -> the previous group appears exactly 6 times
$ -> match end
i -> ignore case

If you need support for 3-character HEX codes, use the following:

/^#([0-9A-F]{3}){1,2}$/i.test('#ABC')

The only difference here is that

 [0-9A-F]{6}

is replaced with

([0-9A-F]{3}){1,2}

This means that instead of matching exactly 6 characters, it will match exactly 3 characters, but only 1 or 2 times. Allowing ABC and AABBCC, but not ABCD


// regular functionfunction isHexColor (hex) {  return typeof hex === 'string'      && hex.length === 6      && !isNaN(Number('0x' + hex))}// or as arrow function (ES6+)isHexColor = hex => typeof hex === 'string' && hex.length === 6 && !isNaN(Number('0x' + hex))console.log(isHexColor('AABBCC'))   // trueconsole.log(isHexColor('AABBCC11')) // falseconsole.log(isHexColor('XXBBCC'))   // falseconsole.log(isHexColor('AAXXCC'))   // false