十六进制颜色和RGB颜色互转函数

 

RGB颜色格式正则:/^(rgb|RGB)\(((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])(,|, )){2}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\)$/

十六进制颜色正则:/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/

转换数字为十六进制:Number(num).toString(16)

十六进制转十进制:parseInt(num, 16)  

 

 

 

/*
  该函数实现十六进制和RGB颜色互转
*/
String.prototype.convertColor =  function() {
  var sColor = this.toLowerCase(),
      replaceRgb = /^[a-zA-Z]*|#|\(|\)/g,
      //rgb颜色正则
      expRgb = /^(rgb|RGB)\(((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])(,|, )){2}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\)$/,
      //十六进制颜色正则
      expHex = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,
      aHex = [],
      aRgb = [];

  // convert hex to rgb
  if(expRgb.test(sColor)) {
    sColor = sColor.replace(replaceRgb, "").split(",");
    for (var i = 0, j = sColor.length; i < j; i++) {
      aRgb[i] = Number(sColor[i]).toString(16);
      if(aRgb[i].length < 2) {
        aRgb[i] = "0" + aRgb[i];
      }
    }
    return "#" + aRgb.join("");

  // convert rgb to hex
  } else if(expHex.test(sColor)) {
    sColor = sColor.replace(/#/g, "");
    for (var i = 0, en = sColor.length; i < 3; i++) {
      if(len === 3) {
        aHex[i] = sColor.substr(i, 1);
        aHex[i] += aHex[i];
      } else {
        aHex[i] = sColor.substr(i*2, 2);
      }
      aHex[i] = parseInt(aHex[i], 16);
    }
    return "rgb(" + aHex.join(",") + ")";
  }

  // can not convert
  return sColor;
} 

//调用方法:
"rgb(255,0,255)".convertColor();