สตริงถือเป็นรหัสฐานสิบหกที่ถูกต้องได้หากไม่มีอักขระอื่นนอกจากตัวอักษร 0-9 และ a-f
ตัวอย่างเช่น −
'3423ad' is a valid hex code '4234es' is an invalid hex code
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงและตรวจสอบว่าเป็นรหัสฐานสิบหกที่ถูกต้องหรือไม่
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
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)); ผลลัพธ์
ต่อไปนี้เป็นผลลัพธ์ในคอนโซล -
false true