ตรวจสอบว่าสตริงประกอบด้วยตัวอักษร hexadecimal เท่านั้น (0-9, a-f)
ตัวอย่าง
'3423ad' // valid '4234es' // invalid (มี 's')
ตัวอย่างโค้ด
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)); // false
console.log(isHexValid(str2)); // true
วิธีทันสมัยกว่า (Regex)
const isHexValid = str => /^[0-9a-f]+$/i.test(str);
ผลลัพธ์
false true
ประยุกต์ใช้: การตรวจสอบสี hex color code การตรวจสอบ hash การ validate input