Open In App

JavaScript Check if a string is a valid hex color representation

Given a hex color code and the task is to check whether the given hexCode is valid or not using JavaScript. We are going to discuss a few techniques. 

Approach:



Example 1: In this example, the validity of the hexcode is checked by Regular Expression. 




let colorCode = '#zabbcc';
 
let Reg_Exp = /^#[0-9A-F]{6}$/i;
 
console.log(Reg_Exp.test(colorCode));

Output

false

Example 2: This example does much more advanced checking than the previous example. In this example also, the validity of the hexcode is checked. 




let colorCode = '#aabbcc';
 
let Reg_Exp = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i;
 
console.log(Reg_Exp.test(colorCode));

Output
true
Article Tags :