regex javascript to match both RGB and RGBA

It’s not so simple- an rgb is illegal with a fourth parameter.
You also need to allow for percentage decimals as well as integer values
for the rgb numbers. And spaces are allowed almost anywhere.

function getRgbish(c){
    var i= 0, itm,
    M= c.replace(/ +/g, '').match(/(rgba?)|(\d+(\.\d+)?%?)|(\.\d+)/g);
    if(M && M.length> 3){
        while(i<3){
            itm= M[++i];
            if(itm.indexOf('%')!= -1){
                itm= Math.round(parseFloat(itm)*2.55);
            }
            else itm= parseInt(itm);
            if(itm<0 || itm> 255) return NaN;
            M[i]= itm;
        }
        if(c.indexOf('rgba')=== 0){
            if(M[4]==undefined ||M[4]<0 || M[4]> 1) return NaN;
        }
        else if(M[4]) return NaN;
        return M[0]+'('+M.slice(1).join(',')+')';
    }
    return NaN;
}

//testing:

var A= ['rgb(100,100,255)',
'rgb(100,100,255,.75)',
'rgba(100,100,255,.75)',
'rgb(100%,100%)',
'rgb(50%,100%,0)',
'rgba(100%,100%,0)',
'rgba(110%,110%,0,1)'];

A.map(getRgbish).join('\n');

returned values:
rgb(100,100,255)
NaN
rgba(100,100,255,.75)
NaN
rgb(127,255,0)
NaN
NaN

Leave a Comment