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
The code for this will be −
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
The output in the console will be −
false true