Search code examples
javascriptjqueryregexcolor-codes

Search and replace hexadecimal color codes with rgb values in a string


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.

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) + ')';
    })