Skip to content

Instantly share code, notes, and snippets.

@jikeytang
Created June 3, 2014 01:13
Show Gist options
  • Save jikeytang/1ca86ae1bf29e41ed179 to your computer and use it in GitHub Desktop.
Save jikeytang/1ca86ae1bf29e41ed179 to your computer and use it in GitHub Desktop.
[ Javascript ] - 20140603-题目1
如何将颜色值十六进制,RGB相互转换?
如:#ffffff转换为:RGB(255,255,255)
RGB(23, 245, 56)转换为:#17f538
PS:
1. 回复时注意加上下面这句话,才会有语法高亮或格式缩进。
```javascript
// you code
```
2. 粘贴代码时请使用shift+tab,缩进前面的空白。
@rambo-panda
Copy link

// 昨天没看到 相互转换 失误失误  正好昨天浏览网页的时候,发现竟然还有人写这个库 http://www.zhangxinxu.com/study/js/zxx.color_exchange.js
var colorHex = function(rgb){
    rgb = rgb.replace(/(rgb|RGB|\(|\))/g,'').split(',');
    var result ='';
    while(1){
        if(!rgb[0]){
            return '#' + result;
        }
        result += (rgb.shift()-0).toString(16);
    }
}

@sunnylost
Copy link

function convert(str) {
    var rhex   = /\#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/;
    var rrgb   = /RGB\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;
    var rblank = /\s*/g;
    var match;

    str = str ? str.replace(rblank, '') : '';

    if(match = str.match(rhex)) {
        return toRGB(match);
    } else if(match = str.match(rrgb)) {
        return toHex(match);
    } else {
        throw Error('Invalid format.');
    }
}

function toHex(rgb) {
    var result = '';
    var item;

    for(var i = 1; i <= 3; i++) {
        item = +rgb[i];
        result += '0'.substring(Math.floor(item / 16)) + item.toString(16);
    }

    return '#' + result;
}

function toRGB(hex) {
    var result = '';

    for(var i = 1; i <= 3; i++) {
        result += parseInt(hex[i], 16) + ',';
    }

    return 'RGB(' + result.substring(0, result.length - 1) + ')';
}

console.log(convert('#172dff'));
console.log(convert('RGB(2, 45, 255)'));

@zjhsd2007
Copy link

建议考虑一下#333和#FFF的情况

@hjzheng
Copy link

hjzheng commented Jun 3, 2014

"#" + "RGB(23, 245, 56)".match(/\d+/g).map(function(num){ return (num-0).toString(16) }).join("");
"RGB(" + "#17f538".match(/\w{2}/g).map(function(str){ return parseInt(str, 16)}).join(",") + ")";

@xianlaioy
Copy link

       function pInt(s, mag) {
       return parseInt(s, mag || 10);
       }
    function init(input) {
            // declare variables
           var rgba = [], result;
        // rgba
        if((result = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/.exec(input))) {
            rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)];
        }

        // hex
        else if((result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(input))) {
            rgba = [pInt(result[1],16), pInt(result[2],16), pInt(result[3],16), 1];
        }

    }

@karrynew
Copy link

karrynew commented Jun 4, 2014

呵呵 一道面试题

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment