简体   繁体   中英

Need some tips with how to convert a hexadecimal color value to a rgb() one

I just started reading Object-Oriented JavaScript and am stuck on an exercise.

On page 91 it asks to write a function that converts a hex color into its RGB equivalent (eg "rgb(0,0,255)"). It requires that you pull in the full string including the '#'.

After reading through the two chapters he has spent on explaining data types, loops, conditions,and functions I don't know how to parse the hex value without cheating and using some sort of string function - something he hasn't even covered at this point.

Is there a way you can do this exercise using only the functions and methods he's demonstrated in the book? He asks that javascript return "rgb(0,255,0)" if the following code is entered:

var a = getRGB("#00FF00");
a;

I'm assuming you would need to break up the hex value into an array for the r,g and b values using a loop and then recombine them into the string. If possible, please don't give me the entire solution but any helpful hints would be greatly appreciated. Thanks for any help.

I noticed you said without any string methods. Here is how to do the first part with only Array methods...

  • Use split() to turn the string into an array.
  • Swap the substr() calls with slice() .

However, in the Real World, you can use substr() to extract portions of a string. The first argument is the offset, the second is the number of characters to extract.

You can then use parseInt() to change the base of the number. You simply pass in the number (as a string) as the first argument, and the base as the second. I chose the radix of 16 as these are hexadecimal numbers.

You can then concatenate the return values with rgb(x,x,x) string portion and you are good to go :)

You can mouseover below to see the code (if you get stuck). BTW, does anyone know how to make a block level code spoiler?

var getRGB = function(rgb) { var r = rgb.substr(1, 2), g = rgb.substr(3, 2), b = rgb.substr(5, 2);
return 'rgb(' + parseInt(r, 16) + ',' + parseInt(g, 16) + ',' + parseInt(b, 16) + ')'; }

jsFiddle .

Once you have figured this out, the next step may be to allow the function to accept the short form of RGB that browsers allow, ie your example #00FF00 could be passed as #0F0 .

Some tips...

  • Check the string length first with rgb.length .
  • Alter your substr() calls dependent on the length.
  • Build the strings you pass to parseInt() so F becomes FF .

Get the input string and replace the # with nothing, then parse it to an integer using parseInt() and send 16 as the numeric base, now you have a long integer where the first 8 bits are the blue value, the bits from 9 to 16 are the green value and the bits from 17 to 24 are the red value. Use bit shifting and masking to pull them out. Put it all into a string like "rgb(r,g,b)", congrats, your done.

function parseRGB(Hex)
{
    var Word = parseInt(Hex.replace(/^#/, ""), 16);
    var R = Word >> 16 & 0xff;
    var G = Word >> 8 & 0xff;
    var B = Word & 0xff;

    return "rgb(" + R + ", " + G + ", " + B + ")";
}
var c = "#00ff00";
alert(parseRGB(c));

Another 2-bit method, suitable for using input strings

function hextoRgb(hex){
    if(/^#[a-fA-F0-9]{6}$/.test(hex)){
        var c= '0x'+hex.substring(1);
        c= [(c>> 16)&255, (c>> 8)&255, c&255];
        return 'rgb('+c.join(',')+')';
    }
    throw 'bad hex '+hex;
}

I won't give myself credit for answering the question but I thought I would share the result of emailing the author (I guess you can do that these days!!!). He provided me a tip and here is what I came up with which works as he asked it to:

function getRGB(x){
var a =[];
a[0] = parseInt(x[1] + x[2],16);
a[1] = parseInt(x[3] + x[4],16);
a[2] = parseInt(x[5] + x[6],16);
a = "rgb(" + a[0] + "," + a[1] + "," + a[2] + ")";   
return a;

}

var a = getRGB("#00FF00"); a;

try mine use array

function getRGB(hex){
     var s = [],i ;
     for (i = 1; i < 7; i+=2) {
         s[i] = parseInt(hex[i]+(hex[i+1]),16);
     }
     return `rgb(${s[1]},${s[3]},${s[5]})`;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM