子串,拆分,字符串到数字和RGB到HEX

时间:2016-10-09 07:59:39

标签: javascript arrays regex ecmascript-6

我认为这是一项简单的任务,但它变得非常复杂。见代码。

    // Convert "rgb(255, 255, 255)" to (255, 255, 255) and then to Hex code
    var data = {
        color:"rgb(165,199,72)",
        color:"rgb(229,121,74)",
        color:"rgb(105,177,222)"        
    }
    // rgb To Hex Conversion
    var componentToHex = function(c) {            
        var hex = c.toString(16);
        return hex.length == 1 ? "0" + hex : hex;
    }       
    var rgbHex = function(r, g, b) {
        return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
    }


    //Substring "rgb(255, 255, 255)" to "(255, 255, 255)"
    var subStringRGB = function(c){
        var b = c.substring(4, c.length);
    }
    var stringRGBtoNumber = function(c){
        var b = Number(c.split(','));
    }

它是抛出错误,无法读取未定义的拆分。如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

subStringRGB不会返回值。因此,如果您将subStringRGB的结果传递给stringRGBtoNumber cundefined中的结果可能会stringRGBtoNumber。顺便说一句,stringRGBtoNumber也没有返回值。

答案 1 :(得分:1)

使用正则表达式处理它很容易。

var arr = /rgb(\((\d+),(\d+),(\d+)\))/.exec("rgb(255,255,255)");
console.log(arr[1]); // it shows (255,255,255)
var hexVal = (parseInt(arr[2]) << 16) + (parseInt(arr[3]) << 8) + parseInt(arr[4]); // calculate the decimal value
console.log("0x" + hexVal.toString(16)); // it shows 0xffffff

答案 2 :(得分:1)

你可以将这些函数组合成带有扩展运算符的单行和一些值的部分映射。

subStringRGBstringRGBtoNumber现在返回已处理的值。

&#13;
&#13;
var data = [{ color:"rgb(165,199,72)"}, { color:"rgb(229,121,74)" },{ color:"rgb(105,177,222)" }],        
    componentToHex = function(c) {            
        var hex = c.toString(16);
        return hex.length == 1 ? "0" + hex : hex;
    },
    rgbHex = function(r, g, b) {
        return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
    },
    subStringRGB = function(c){
        return c.slice(4, -1);
    },
    stringRGBtoNumber = function(c){
        return c.split(',').map(Number); // split and convert all parts to Number
    };
    
console.log(data.map(c => rgbHex(...stringRGBtoNumber(subStringRGB(c.color)).map(componentToHex))));
&#13;
&#13;
&#13;

相关问题