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

js type automatic conversion

js type automatic conversion

String & Number


`255` < 16;
false
`15` < 16;
true
`25` < 16;
false
`15` + 16;
"1516"
`15` * 16;
240
`15` - 16;
-1
`15` / 16;
0.9375

demo

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);
    })
  }
}
// OK ✅
/^(rgb|RGB)\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)/

// Error ❌
/^rgb\([\s*\d+,]{2}[\s*\d+]{1}\)$/

refs

https://regexper.com/#%2F^(rgb|RGB)\((\d{1%2C3})%2C\s%28%5Cd%7B1%2C3%7D%29%2C%5Cs%28%5Cd%7B1%2C3%7D%29%5C%29%2F



©xgqfrms 2012-2020

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


posted @ 2020-08-24 23:12  xgqfrms  阅读(213)  评论(4编辑  收藏  举报