3

I want to modify the color attribute that is returned in JQuery. So, lets assume the color is returned and is contained in a

var color
color = 'rgb(148, 141, 124)'

I want to modify the value of color to be:

color = 'rgb(148, 141, 124, .7)'

(in other words, insert the string ", .7")

1
  • 1
    Just make the first tag like this color = 'rgba(148, 141, 124,1)' that will do the work easy for the next line.. color = 'rgba(148, 141, 124,.7)' just change last value from 1 to .7 :) and make sure RGB and RGBA are different only RGB works in some browser but some browser might not work! Commented Jun 27, 2014 at 5:04

4 Answers 4

5

Try,

var color = 'rgb(148, 141, 124)';
var newColor = color.slice(0,-1) + ",.7)"

DEMO

If you want it to be rgba then use,

var color = 'rgb(148, 141, 124)';
var newColor = (color.slice(0,-1) + ",.7)").split('(').join('a(');

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

It still needs the a in the rgba. OP forgot about that.
2

You could do like below:

color = color.replace(/\)/, ', 0.7)')

1 Comment

Yes,I am curious too.What's wrong with this expression?
1

Similar to above, slightly different method:

var color = 'rgb(148, 141, 124)';
var colorAlpha = color.replace(/rgb/g, 'rgba').replace(/\)/g, ', 0.7)');

FIDDLE

OR, as someone commented on the above, it could be simpler to add the alpha to the original variable, and just replace that number in the new string:

var color = 'rgba(148, 141, 124, 1.0)';
var colorAlpha = color.replace(/1.0/g, '0.7');
alert(colorAlpha);

1 Comment

I guess I just wanted to temp the mysterious Captain Downvote. Success!
0

Using .split() also you can easily achieve your goal

var color = 'rgb(148, 141, 124)';
var newColor = color.split(")")[0];

alert(newColor + ', 0.7)');

DEMO

Comments

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.