在 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

更新於: 2020 年 10 月 19 日

136 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.