Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 digits and a-f alphabets (case-insensitive). Hex codes are commonly used in web development for colors, cryptographic hashes, and other applications.
For example:
'3423ad' is a valid hex code '4234es' is an invalid hex code (contains 'e' and 's')
We need to write a JavaScript function that takes in a string and checks whether it's a valid hex code or not.
Method 1: Using includes() Method
This approach checks each character against a string containing all valid hex characters:
const str1 = '4234es';
const str2 = '3423ad';
const isHexValid = str => {
const legend = '0123456789abcdef';
for(let i = 0; i
false
true
Method 2: Using Regular Expression
A more concise approach using regex to match only valid hex characters:
const isHexValidRegex = str => {
return /^[0-9a-fA-F]+$/.test(str);
};
console.log(isHexValidRegex('3423ad')); // true
console.log(isHexValidRegex('4234es')); // false
console.log(isHexValidRegex('FF00AA')); // true (uppercase)
console.log(isHexValidRegex('')); // false (empty string)
true
false
true
false
Method 3: Using every() Method
Using the every() method to check if all characters are valid:
const isHexValidEvery = str => {
if (str.length === 0) return false;
return str.split('').every(char => '0123456789abcdefABCDEF'.includes(char));
};
console.log(isHexValidEvery('abc123')); // true
console.log(isHexValidEvery('xyz789')); // false
console.log(isHexValidEvery('DEADBEEF')); // true
true
false
true
Comparison
| Method | Performance | Readability | Case Handling |
|---|---|---|---|
| includes() with loop | Good | Moderate | Manual (toLowerCase) |
| Regular Expression | Best | Best | Built-in [a-fA-F] |
| every() method | Good | Good | Manual (include both cases) |
Enhanced Validation
For practical use cases, you might want to validate hex codes with specific lengths (like 6 for colors):
const isValidHexColor = str => {
return /^[0-9a-fA-F]{6}$/.test(str);
};
console.log(isValidHexColor('FF0000')); // true (6 characters)
console.log(isValidHexColor('FFF')); // false (3 characters)
console.log(isValidHexColor('GG0000')); // false (invalid chars)
true false false
Conclusion
The regular expression method /^[0-9a-fA-F]+$/.test(str) is the most efficient and readable approach for validating hex codes. For specific use cases like color codes, you can modify the regex to enforce exact length requirements.
