简体   繁体   中英

How to convert an indeterminate number of rgb occurrences in a string to hex in JavaScript?

Fireworks CS6 includes a panel that copies the CSS3 properties of the selected object.

However, the code is overly verbose and messy, so I'd like to write an extension in JavaScript that cleans it up.

I've done everything I need, except figuring out how to convert any number of rgb values in to their smaller hex code equivalents.

For example, a typical string it returns for gradients may include this:

background: -moz-linear-gradient(50% 0% -87deg, rgb(0,0,0) 0%, rgb(0,255,64) 28%, rgb(0,177,122) 40%, rgb(0,0,255) 68%, rgb(37,37,230) 76%, rgb(153,153,153) 100%); 
background: -ms-linear-gradient(-87deg, rgb(0,0,0) 0%, rgb(0,255,64) 28%, rgb(0,177,122) 40%, rgb(0,0,255) 68%, rgb(37,37,230) 76%, rgb(153,153,153) 100%);
background: -o-linear-gradient(-87deg, rgb(0,0,0) 0%, rgb(0,255,64) 28%, rgb(0,177,122) 40%, rgb(0,0,255) 68%, rgb(37,37,230) 76%, rgb(153,153,153) 100%);
background: -webkit-gradient(linear,50% 0%,55% 100%, color-stop(0, rgb(0,0,0)), color-stop(0.28, rgb(0,255,64)), color-stop(0.4, rgb(0,177,122)), color-stop(0.68, rgb(0,0,255)), color-stop(0.76, rgb(37,37,230)), color-stop(1, rgb(153,153,153)));
background: -webkit-linear-gradient(-87deg, rgb(0,0,0) 0%, rgb(0,255,64) 28%, rgb(0,177,122) 40%, rgb(0,0,255) 68%, rgb(37,37,230) 76%, rgb(153,153,153) 100%);
background: linear-gradient(-87deg, rgb(0,0,0) 0%, rgb(0,255,64) 28%, rgb(0,177,122) 40%, rgb(0,0,255) 68%, rgb(37,37,230) 76%, rgb(153,153,153) 100%);
border-color: rgb(198,34,221);

I already have a function that will convert r,g,b values to their hex equivalent, but I'm not sure how I would go about looping through the string and isolating the rgb components & converting each one.

If you only want to capture this exact syntax - rgb with three decimal numbers without white spaces, then string.replace(/rgb\\((\\d+),(\\d+),(\\d+)\\)/g, yourFunction) will do. First parameter will be entire rgb() sequence and next three will be R, G and B numbers. You will need to return new string to replace entire rgb().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM