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,缩进前面的空白。
@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