How to check if a string is a valid hex color representation?

后端 未结 7 487
迷失自我
迷失自我 2020-11-28 03:47

For example:

AA33FF = valid hex color

Z34FF9 = invalid hex color (has Z in it)

AA33FF11 = invalid hex color (h

相关标签:
7条回答
  • 2020-11-28 04:29

    // regular function
    function isHexColor (hex) {
      return typeof hex === 'string'
          && hex.length === 6
          && !isNaN(Number('0x' + hex))
    }
    
    // or as arrow function (ES6+)
    isHexColor = hex => typeof hex === 'string' && hex.length === 6 && !isNaN(Number('0x' + hex))
    
    console.log(isHexColor('AABBCC'))   // true
    console.log(isHexColor('AABBCC11')) // false
    console.log(isHexColor('XXBBCC'))   // false
    console.log(isHexColor('AAXXCC'))   // false

    This answer used to throw false positives because instead of Number('0x' + hex), it used parseInt(hex, 16).
    parseInt() will parse from the beginning of the string until it reaches a character that isn't included in the radix (16). This means it could parse strings like 'AAXXCC', because it starts with 'AA'.

    Number(), on the other hand, will only parse if the whole string matches the radix. Now, Number() doesn't take a radix parameter, but luckily, you can prefix number literals to get a number in other radii.

    Here's a table for clarification:

    ╭─────────────┬────────────┬────────┬───────────────────╮
    │ Radix       │ Characters │ Prefix │ Will output 27    │
    ╞═════════════╪════════════╪════════╪═══════════════════╡
    │ Binary      │ 0-1        │ 0b     │ Number('0b11011') │
    │ Octal       │ 0-7        │ 0o     │ Number('0o33')    │
    │ Decimal     │ 0-9        │ -      │ -                 │
    │ Hexadecimal │ 0-9A-F     │ 0x     │ Number('0x1b')    │
    ╰─────────────┴────────────┴────────┴───────────────────╯
    
    0 讨论(0)
提交回复
热议问题