Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To validate hex color string using regex, use /^#(?:[0-9a-f]{3}){1,2}$/i it will handle hex color.

Let’s see short example of javascript regex for hex color.

const regex = /^#(?:[0-9a-f]{3}){1,2}$/i;
console.log(regex.test("#123abc"))

Today, I’m going to show you How do I check value contain hex color in javascript, as above mentioned, I’m going to use the above-mentioned regex with test() method.

Let’s start today’s tutorial how do you check hex color in javascript using regex?

Here, I will show validate hex color in javascript and typescript.

Javascript regex for hex color example

Here, we will create common validate function where we will validate param should hex color.

function validate(param){
  const regex = /^#(?:[0-9a-f]{3}){1,2}$/i;
  return regex.test(param);
}

// validate empty string
console.log(validate(""))
// false

// validate three letter color
console.log(validate("#12a"))
// true

// validate six letter color
console.log(validate("#83af83"))
// true

// validate color without #
console.log(validate("123abc"))
// false

// validate four char
console.log(validate("#82ab"))
// false

// validate other char
console.log(validate("#okeyto"))
// false

Output

Typescript regex for hex color example

Same like javascript, we will create a function and call it with diffrent parameters.

function validate(param: string){
  const regex = /^#(?:[0-9a-f]{3}){1,2}$/i;
  return regex.test(param);
}

// validate empty string
console.log(validate(""))
// false

// validate three letter color
console.log(validate("#12a"))
// true

// validate six letter color
console.log(validate("#83af83"))
// true

// validate color without #
console.log(validate("123abc"))
// false

// validate four char
console.log(validate("#82ab"))
// false

// validate other char
console.log(validate("#okeyto"))
// false

Output

I hope it helps you, All the best đź‘Ť.