Question

I have the HTML source of an element. I want to search all the hexadecimal color codes in it and replace them with their RGB equivalents. How can I do that using JavaScript?

E.g.:

This is <span style="color:#FF0000">red</span> and <span style="color:#3C9310">green</span> color.

should be replaced with

This is <span style="color: rgb(255, 0, 0)">red</span> and <span style="color: rgb(60, 147, 16)">green</span> color.
Was it helpful?

Solution

If you want to convert all hex colours into decimal RGB values in the string str, the following will do the trick. Note that this only considers 8-bit/channel hex values (e.g., #FF0000) and not the 4-bit variants (e.g., #F00); however, this would be easy enough to enhance.

var rgbHex = /#([0-9A-F][0-9A-F])([0-9A-F][0-9A-F])([0-9A-F][0-9A-F])/gi
str.replace(rgbHex, function (m, r, g, b) {
  return 'rgb(' + parseInt(r,16) + ','
                + parseInt(g,16) + ','
                + parseInt(b,16) + ')';
})

OTHER TIPS

You can use jquery css('color').

Live Demo

$('#spcolor').css('color')

For iterating through many elements have same class.

Live Demo

$('.someclass').each(function(){
   alert($(this).css('color'))    
});

Using the function shown here, you can change the colour property of all elements on the page that have it set from Hex to RGB:

var all = document.getElementsByTagName("*");
var elemCount = all.length;

for (var i=0; i < elemCount; i++) {
    if(all[i].style.color && all[i].style.color.indexOf('#') > -1){ //Check if the color property is set, and if it's hex.
        all[i].style.color = hex2rgb(all[i].style.color)
    }
}

You can do something like:

rgbval = "rgb("
"#ff0000".replace(/[a-z0-9]{2}/g, function(val) {rgbval  += (parseInt(val, 16)) + ","})
rgbval  += ")"

The will add an extra comma at the end like rgb(255,0,0,) but i think you can remove it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top