驗證有效的十六進位制程式碼 - JavaScript


如果字串僅包含 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

更新日期: 16-9-2020

575 次瀏覽

助力 職業

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.