Parse hexadecimal color value to rgb three channel using regex

// 将十六进制的颜色值转为rgb 包括#eee(简写)或者#63FFCB(全写)的情况
function hexToRgb(color) {
    
    
    var result = /^#?([a-f\d]{1,2})([a-f\d]{1,2})([a-f\d]{1,2})$/i.exec(color);
    return result ? {
    
    
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

let color = hexToRgb("#63FFCB");
console.log(color); // {r:99, g:255, b:203}
let colorRgb = `rgb(${
      
      color.r},${
      
      color.g},${
      
      color.b})`;
console.log("转成rgb:", colorRgb); // rgb(99,255,203)

Conversion results from the online conversion tool test:
insert image description here

Guess you like

Origin blog.csdn.net/qq_43523725/article/details/120304838