Check for Valid hex code - JavaScript


A string can be considered as a valid hex code if it contains no characters other than the 0-9 and a-f alphabets

For example −

'3423ad' is a valid hex code
'4234es' is an invalid hex code

We are required to write a JavaScript function that takes in a string and checks whether its a valid hex code or not.

Example

Following is the code −

const str1 = '4234es';
const str2 = '3423ad';
const isHexValid = str => {
   const legend = '0123456789abcdef';
   for(let i = 0; i < str.length; i++){
      if(legend.includes(str[i])){
         continue;
      };
      return false;
   };
   return true;
};
console.log(isHexValid(str1));
console.log(isHexValid(str2));

Output

Following is the output in the console −

false
true

Updated on: 16-Sep-2020

488 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements