Search code examples
javascriptjqueryregex

Quick Regex/Replace for rgba(..) from various rgb/rgba strings


I have various color definitions as follows,

i.cat1{background:rgb(249, 115, 0);}  // RGB with 3 params
i.cat2{background:rgba(14, 48, 71, 0.99);}  // RGBA with 4 params

My goal is to set a new rgba(x,y,z,opacity) with a pre-defined opacity variable, say 0.4 (regardless of previous opacity if existed); but x,y,z from the existing values, which are guaranteed to exist.

Ex.

from #1:   rgb(249,115,0)      --> rgba(249,115,0,0.4)
from #2:   rgba(14,48,71,0.99) --> rgba(14,48,71,0.4)

Any quick regex solutions, other than parsing the tokens inside the parentheses and checking if it's 3 or 4 params?

Of course, we can do str.replace('rgb(', 'rgba('); as the first step, but I just want a quick 4-param expression.

Assume I'm getting the current color as a string, say var color is the original str, so this is a regexp question.


Solution

  • var test = [
        "rgb(249,115,0)",
        "rgba(14,48,71,0.99)",
    ];
    console.log(test.map(function (a) {
      return a.replace(/rgba?(\(\s*\d+\s*,\s*\d+\s*,\s*\d+)(?:\s*,.+?)?\)/, 'rgba$1,0.4)');
    }));