ภาพรวม
บทความนี้สาธิตวิธีตรวจสอบว่าสตริงเป็น Valid Hex Code หรือไม่ โดย Hex Code ที่ถูกต้องประกอบด้วยตัวอักษร 0-9 และ a-f (หรือ A-F) เท่านั้น
ตัวอย่าง
'3423ad' -> Valid
'4234es' -> Invalid (มี 's' ซึ่งไม่อยู่ใน 0-9, a-f)
การนำไปใช้
const isHexValid = (str) => {
const legend = '0123456789abcdef';
for (let i = 0; i < str.length; i++) {
if (!legend.includes(str[i].toLowerCase())) {
return false;
}
}
return true;
};
console.log(isHexValid('4234es')); // false
console.log(isHexValid('3423ad')); // true
ผลลัพธ์
false true
วิธีการทันสมัย (Regex) - แนะนำ
// แบบไม่มี Prefix (แค่ Hex Digits)
const isHexValidRegex = (str) => /^[0-9a-fA-F]+$/.test(str);
// แบบมี Prefix # (Color Hex)
const isColorHex = (str) => /^#[0-9a-fA-F]{3,8}$/.test(str);
// แบบมี Prefix 0x
const isHexWithPrefix = (str) => /^0x[0-9a-fA-F]+$/i.test(str);
การแปลง Hex String เป็น Number
const hexToNumber = (hex) => {
if (!/^[0-9a-fA-F]+$/.test(hex)) return NaN;
return parseInt(hex, 16);
};
console.log(hexToNumber('ff')); // 255
console.log(hexToNumber('1a3f')); // 6719
การสร้าง Random Hex Color
const randomHexColor = () =>
'#' + Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, '0');
การประยุกต์ใช้
- Color Validation (CSS Colors)
- Hash Verification (MD5, SHA Hex Output)
- Binary Data Encoding/Decoding
- CSS-in-JS Validation
- Blockchain: Address/Transaction Hash Validation
ข้อควรระวัง
- Case Insensitive: a-f และ A-F ต้องยอมรับทั้งคู่
- Empty String: ตัดสินใจว่ายอมรับหรือไม่ (โค้ดตัวอย่างยอมรับ)
- Prefix: #, 0x, 0X - ต้องระบุชัดเจนว่ารองรับหรือไม่
- Length: สี Hex มักเป็น 3, 4, 6, หรือ 8 ตัวอักษร