Radex Radex - 1 year ago 58
Javascript Question

How to avoid using twice replace (using only one regex) in the following script?

I need to edit a string from:

rgb(250, 0, 0) 10px 10px 50px 0px


rgba(250, 0, 0, 1) 10px 10px 50px 0px

Assuming the input value is always correct, I need to add alpha channel of 1.

The follow script I created works, but I was wondering about the double replace.

I would like to know if you perform a better way, maybe using only one
and avoiding using
twice or a better alternative.

var _convertBoxShadowToTgba = function (boxShadow) {
return boxShadow.replace(/rgb/i, 'rgba').replace(/\)/i, ', 1)');
var original = "rgb(250, 0, 0) 10px 10px 50px 0px";
var final = _convertBoxShadowToTgba(original);
console.log('original', original);
console.log('final', final);

Answer Source




rgb          # Match literal `rgb`
    (        # Start of capturing group (1)
        .*?  # Match every thing lazily
        \d   # Up to a digit
    )        # End of capturing group (1)
\)           # That is followed by a closing bracket

Replacement string:

rgba$1, 1)

$1 is a back-reference to first capturing group

JS code:

original.replace(/rgb(.*?\d)\)/i, 'rgba$1, 1)')

Live demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download