xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Regular Expression & rgb2hex All In One

Regular Expression & rgb2hex All In One

regex

// 颜色字符串转换
function rgb2hex(sRGB = 'rgb(255, 255, 255)') {
  const temp = sRGB;
  // /^rgb\([\s*\d+,]{2}[\s*\d+]\)$/
  if(/^rgb\([\s*\d+,]{2}[\s*\d+]{1}\)$/.test(temp)) {
    // 符合 rgb 格式
  } else {
    // 输入不符合 rgb 格式,返回原始输入
    return temp;
  }
}

function rgb2hex (sRGB = 'rgb(255, 255, 255)') {
  const regex = /^(rgb|RGB)\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)/;
  if(!regex.test(sRGB)){
    return sRGB;
  }else {
    function hex(str) {
      // string < number ❓⚠️
      return str < 16 ? "0" + Number(str).toString(16) : Number(str).toString(16);
    }
    return sRGB.replace(regex, function(a, c, r, g, b){
      console.log(`a, c`, a, c);
      console.log(`r, g, b`, r, g, b);
      console.log(`typeof r, typeof g, typeof b`, typeof r, typeof g, typeof b);
      // console.log(`a, c, r, g, b`, a, c, r, g, b);
      return "#" + hex(r) + hex(g) + hex(b);
    })
  }
}


function rgb2hex (sRGB = 'rgb(255, 255, 255)') {
  const rgbStr = sRGB.toLowerCase();
  // rgb 50%, RGB 50%
  const regex = /^(rgb|RGB)\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)/;
  // const regex = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)/;
  if(!regex.test(rgbStr)){
    return sRGB;
  }else {
    function hex(str) {
      return str < 16 ? "0" + Number(str).toString(16) : Number(str).toString(16);
    }
    return rgbStr.toLowerCase().replace(regex, function(a, c, r, g, b){
      console.log(`a, c`, a, c);
      console.log(`r, g, b`, r, g, b);
      // console.log(`a, c, r, g, b`, a, c, r, g, b);
      return "#" + hex(r) + hex(g) + hex(b);
    })
  }
}

demos

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://regexper.com/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Cheatsheet



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2020-08-24 17:02  xgqfrms  阅读(129)  评论(6编辑  收藏  举报