Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

Today, I’m going to show how do you check if a string is hexadecimal in javascript, here I will use the regex expression to check string is a hex code or not.

Here, we will write reg expression for validating string hex code, and javascript provides test() method validate string using regex, we are also going to do same.

Let’s start today’s tutorial How to check if a string is hexadecimal in javascript?

Here, we will do

  1. Write regex code which we will use
  2. Create valid and invalid hex code variables
  3. Use regex and test method to validate string
  4. Console which strings valid hex code which is not
// Write regx code which we will use
let regExp = /^#([0-9a-f]{3}){1,2}$/i;

// Create valid and invalid hex code variables
let validHex = "#AABBCC";
let invalidHex = "#GHIJKL";

// Use regex and test method to validate string
// Console which string valid hex code which is not
if(regExp.test(validHex)){
	console.log("validHex have valid hex code.")
}

if(regExp.test(invalidHex)){
	console.log("invalidHex have valid hex code.")
}

When you run the above program, it will console which string variable contains valid hex code, let’s check the output.

javascript, check if a string is hexadecimal example
javascript, check if a string is hexadecimal example

I hope it’s help you, All the best 👍.