Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change an rgb value in a javascript string of css styles to hex value with regex + replace

Tags:

regex

replace

I have been struggling with this for a while now so I thought I would ask here to see if anyone can help me out.

I have a string of css styles in javascript which looks like this:

width: 250px; background-color: rgb(48, 44, 48);

I am trying to replace the rgb value in the string with a hex value by running it through a function I have called RGBtoHEX so I am left with a string like the following:

width: 250px; background-color: #302C30;

I am struggling to create the regex to get the rgb string from the main string to pass to the function.

Any help with this would be great.

Thanks for looking

like image 833
Rob Taylor Avatar asked Nov 27 '25 09:11

Rob Taylor


1 Answers

Try something like this:

str.replace(
    /\brgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/g,
    function($0, $1, $2, $3) {
        return "#" + ("0"+Number($1).toString(16)).substr(-2) + ("0"+Number($2).toString(16)).substr(-2) + ("0"+Number($3).toString(16)).substr(-2);
    })
like image 81
Gumbo Avatar answered Nov 29 '25 23:11

Gumbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!