2

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

2 Answers 2

12

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);
    })
Sign up to request clarification or add additional context in comments.

2 Comments

This works but I have no idea why. Is there anywhere I can read up on how the function inside replace() works? Thanks
@Rob Taylor: The function passed to replace is called for each match and the matches of each sub-pattern is passed to it (first argument is the whole matched string). See Mozilla’s reference for String.prototype.replace for further information. And Number(x).toString(16) is just used to turn the string into hexadecimal.
0

You can try putting the css line in a string and extracting the rgb values character by character.

2 Comments

I already have the css line in a string. How would I extract the rgb values from the string?
Try using the substring() function. Also, for further reference, read w3schools.com/jsref/jsref_obj_string.asp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.