Open In App

JavaScript Check if a string is a valid hex color representation

Last Updated : 20 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Valid hexcode contains the alphabets(A-F) and integers(0-9) and is of length 3 or 6.
  • A RegExp is used to check whether the alphabets ranging between A and F, Integers from 0-9, and is of length = 3 or 6.

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

Javascript




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. 

Javascript




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


Output

true

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads