Jquery # color to rgba?

Is it possible to convert color as such #ff0000 to rgb?

So, convert #ff0000 to rgb(255,0,0);

I am sure that this should be possible, I just do not know how to do it. Any insight would be great!

+5
source share
6 answers

You can use:

 var s = "#ff0000"; var patt = /^#([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})$/; var matches = patt.exec(s); var rgb = "rgb("+parseInt(matches[1], 16)+","+parseInt(matches[2], 16)+","+parseInt(matches[3], 16)+");"; alert(rgb); 
+8
source

.css("background-color") will return rgb http://api.jquery.com/css/

here is the fiddle http://jsfiddle.net/3nigma/msRqv/1/

+6
source

How about this algorithm?

http://www.javascripter.net/faq/hextorgb.htm

You can even create a jQuery plugin that uses this algorithm. I think it would be cool. I do not know if one already exists.

+3
source

Pure work with the string you have, you could something like this:

 var color = '#FF5500'; 

First, extract two hexadecimal digits for each color:

 var redHex = color.substring(1, 3); var greenHex = color.substring(3, 5); var blueHex = color.substring(5, 7); 

Then convert them to decimal numbers:

 var redDec = parseInt(redHex, 16); var greenDec = parseInt(greenHex, 16); var blueDec = parseInt(blueHex, 16); 

And finally, we get your rgb() as a result:

 var colorRgb = 'rgb(' + redDec + ', ' + greenDec + ', ' + blueDec + ')'; console.log( colorRgb ); 

And you get as output:

 rgb(255, 85, 0) 
+3
source

You must separate all three components from the Hex definition, and then convert them to decimal. It works:

 function hex2rgba(x,a) { var r=x.replace('#','').match(/../g),g=[],i; for(i in r){g.push(parseInt(r[i],16));}g.push(a); return 'rgba('+g.join()+')'; } 
+1
source

Source: https://habr.com/ru/post/956964/


All Articles