#21 16 进制颜色值转 RGB 值


  • 0
    administrators

    完成函数 hexToRGB,它的作用将 16 进制颜色值转换成 RGB 值:

    hexToRGB('#F0F0F0') // => rgb(240, 240, 240)
    hexToRGB('#9fc') // => rgb(153, 255, 204)
    hexToRGB('无效颜色') // => null
    

  • 0

    @胡子大哈 0_1495465729681_upload-c0705e82-1cb7-4a47-91b2-955042ce2967

    我输出的是对的啊,不过我没有验证hex,


  • 0
    administrators

    @dcbryant 数字和逗号之间有空格隔开


  • 0

    原来如此,ths


  • 0

    @胡子大哈 0_1495466821378_upload-3b9e8588-f744-4d57-91a3-62cb681271b2

    hex为‘#FFFFFF’,不该为rgb(255, 255, 255)嘛


  • 0
    administrators

    @dcbryant 你数一下有多少个 F 😄


  • 0

    你真的是火眼金睛,惭愧惭愧哈哈


  • 0

    话说这个检测机制好智能啊,最开始的时候还以为有人盯着我答案


  • 0

    const hexToRGB = (hex) => {
      if (!hex) return null
      const color = hex.split('#')
      if(color.length < 0){
        return null
      }
      if (color[1].match(/[g-zG-Z]/)) {
        return null
      }
      if(color[1].length==3) {
        const red = parseInt(color[1].slice(0,1)+color[1].slice(0,1), 16)
        const green = parseInt(color[1].slice(1,2)+color[1].slice(1,2), 16)
        const blue = parseInt(color[1].slice(2,3)+color[1].slice(2,3), 16)
        return 'rgb(' + red + ', ' + green + ', ' + blue + ')'
      } else if (color[1].length==6){
        const red = parseInt(color[1].slice(0,2), 16)
        const green = parseInt(color[1].slice(2,4), 16)
        const blue = parseInt(color[1].slice(4,6), 16)
        return 'rgb(' + red + ', ' + green + ', ' + blue + ')'
      } else {
        return null
      }
    }
    

    好气啊,正则表达式掌握的不熟练 :-(


  • 0

    const hexToRGB = (hex) => {
      let regex = /^\#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;
      if(!regex.test(hex)) {
        return null;
      }
      let num_map = { A: 10,  B: 11, C: 12, D: 13, E: 14, F: 15};
      let r = 0, g = 0, b = 0;
      
      hex = hex.replace('#', '').split('');
      if(hex.length === 3) {
        hex.splice(0, 0, hex[0]);
        hex.splice(2, 0, hex[2]);
        hex.splice(4, 0, hex[4]);
      }
      
      hex = hex.map(h => {
        let int = parseInt(h);
        return (int || int === 0) ? int : num_map[h.toUpperCase()];
      });
      
      r = 16 * hex[0] + hex[1];
      g = 16 * hex[2] + hex[3];
      b = 16 * hex[4] + hex[5];
      
      return `rgb(${r}, ${g}, ${b})`;
    }
    

  • 0

    @ScriptOJ

    if(hex.match(/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/g)) {
    var color = hex.substring(1);
    var rgb = [];
    var index = 0, step = color.length == 3 ? 1 : 2;

    while((index + step) <= color.length) {
      var item = color.substring(index, index + step);
      var rgbItem = color.length == 3 ? item + item : item;
      rgb.push(parseInt(rgbItem,16))
      index += step;
    }
    
    return "rgb(" + rgb.join(", ") + ")";
    

    }
    else {
    return null
    }

    0_1501688705035_upload-5ba04377-029a-413b-8fdb-fd18039d389d


  • 0

    @Colin

    @Colin#21 16 进制颜色值转 RGB 值 中说:

    @ScriptOJ

    if(hex.match(/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/g)) {
    var color = hex.substring(1);
    var rgb = [];
    var index = 0, step = color.length == 3 ? 1 : 2;

    while((index + step) <= color.length) {
      var item = color.substring(index, index + step);
      var rgbItem = color.length == 3 ? item + item : item;
      rgb.push(parseInt(rgbItem,16))
      index += step;
    }
    
    return "rgb(" + rgb.join(", ") + ")";
    

    }
    else {
    return null
    }

    0_1501688705035_upload-5ba04377-029a-413b-8fdb-fd18039d389d

    解决了 hex && hex.match(/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/g)


  • 0

    0_1501760160509_upload-dccef425-ea88-4545-8f8f-68b3ca579912
    这是什么鬼


  • 0

    我就贴贴代码

    const hexToRGB = (hex) => 
    {
      let str = /#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3}/.exec(hex)
      if(str){
        let strArr = String.prototype.split.call(str,"")
        let inputStr = String.prototype.split.call(str.input,"");
        if(strArr.length == 7 && inputStr.length ==7){
          let resultStr = 'rgb('
          for(let i = 1 ; i<7;i= i+2){
            let metaColor = parseInt(strArr[i]+strArr[i+1], 16).toString(); 
            let isComma = (i==1?'':', ') ;
            resultStr = resultStr + isComma+ metaColor;
          }
          resultStr = resultStr + ')'
          return resultStr;
        }
        if(strArr.length == 4 && inputStr.length ==4){
          let resultStr = 'rgb('
          for(let i = 1 ; i<4 ;i++){
            let metaColor = parseInt(strArr[i]+strArr[i], 16).toString(); 
            let isComma = (i==1?'':', ') ;
            resultStr = resultStr + isComma+ metaColor;
          }
          resultStr = resultStr + ')'
          return resultStr;
        }
        return null
      }else{  
        return null;
      }
    }
    

  • 0

    const hexToRGB = (hex) => {
    if (hex){
    let arr = hex.split('#');
    let threetwobitarr = [];
    if (arr.length === 1 || arr[1].length > 6 || arr[1].search(/[^0-9a-fA-F]/) !== -1 {
    return null;
    } else {
    let colorhex = arr[1].split('');
    if (colorhex.length === 6) {
    let twobitarr = colorhex.reduce((acc,val,index,colorhex) => acc.concat(index%2 ===1?
    (colorhex[index-1] + val):''),[]);
    threetwobitarr = twobitarr.filter( v => v!== '');
    } else if (colorhex.length === 3) {
    threetwobitarr = colorhex.map( v => v + v );
    } else {
    return null;
    }
    let tenarr = threetwobitarr.map( v=> parseInt(v,16));
    return tenarr.reduce((a,v,i) => a.concat(i!==2?v + ', ':v + ')'),'rgb(');
    }
    } else return null;
    }


  • 1

    const hexToRGB = (hex) => /* TODO */{
      let o = document.createElement('div');
      o.style.color = hex;
      return o.style.color?o.style.color:null;
    }
    

    代码简洁如我


  • 0

    @ScriptOJ @胡子大哈
    这是我的代码
    var str = hex;
    //var str = '#ffffff';
    str = str.toUpperCase().match(/#(\S*)/)[1];
    var str2 = str.split('');
    var c1,c2,c3,color;
    if(str2.length == 3){
    c1 = to10(str2[0])2;
    c2 = to10(str2[3])2;
    c3 = to10(str2[2])2;
    alert(c1,c2,c3);
    color = "rgb(' + c1 +', ' + c2 + ', ' + c3 + ')";
    return color;
    }else if(str2.length == 6){
    c1 = Number(to10(str2[0]))+Number(to102(str2[1]));
    c2 = Number(to10(str2[2]))+Number(to102(str2[3]));
    c3 = Number(to10(str2[4]))+Number(to102(str2[5]));
    color = "rgb(' + c1 +', ' + c2 + ', ' + c3 + ')";
    return color;
    }else{
    return null;
    }
    function to10(t){
    // t = Number(t);
    if(t == 'A'){
    return 10
    16
    }else if(t == 'B'){
    return 11
    16
    }else if(t == 'C'){
    return 12
    16
    }else if(t == 'D'){
    return 1316
    }else if(t == 'E'){
    return 14
    16
    }else if(t == 'F'){
    return 1516
    }else{
    return t
    16
    }
    }
    function to102(lt){
    // lt = Number(lt);
    if(lt == 'A'){
    return 10
    }else if(lt == 'B'){
    return 11
    }else if(lt =='C'){
    return 12
    }else if(lt == 'D'){
    return 13
    }else if(lt == 'E'){
    return 14
    }else if(lt == 'F'){
    return 15
    }else{
    return lt
    }
    }

    0_1520221267944_QQ图片20180305114028.png
    这个拼接字符的,如果我去掉红色框的两个空格(或者其中一个)那么结果如下图
    0_1520221164816_QQ图片20180305113755.png
    如果我加上红色框的两个空格那么结果如下图
    0_1520221089256_QQ图片20180305113747.png
    这是什么原因呢?请大神解惑


  • 0

    const hexToRGB = (hex) => {
      const regex = /^\#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;
      if(!regex.test(hex)){
        return null;
      }
      let h = hex.slice(1);
      const result = [];
      if(h.length === 3) h = h.replace(/(.)/g,'$&$&');
      h.replace(/../g, color => result.push(parseInt(color, 0x10)));
      
      return `rgb(${result.join(', ')})`;
    }
    

    再补充个RGB转HEX的

    const RGBToHex = (rgb) => {
      const regx = /^rgb\(\d+(\,\s*\d+){2}\)$/g;
      if(!regx.test(rgb)) return null;
      return rgb.slice()
                .match(/\d+/g)
                .reduce((p,c) => p.concat(
                  Number(c).toString(16) // Number.toString(16) 可以转换成16进制的字符串
                            .replace(/^[0-9a-fA-F](?=$)/,'0$&') // 如果结果是1位数,就在前面补0
                ), ['#']).join('');
    }
    
    console.log(
      RGBToHex('rgb(240, 240, 240)'), // #F0F0F0
      RGBToHex('rgb(153, 255, 204)'), // #99ffcc
      RGBToHex('rgb(108, 74, 7)'), // #6c4A07
      RGBToHex('无效颜色'),
    )
    

  • 0

    @qq1448896454 在browser下可以正常运行,但是在node环境下原生是没有document对象的,这样不具备通用性


登录后回复
 

与 ScriptOJ 的连接断开,我们正在尝试重连,请耐心等待