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")
asked Jun 27, 2014 at 4:46
sea26.2
3801 gold badge6 silver badges24 bronze badges
4 Answers 4
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
answered Jun 27, 2014 at 4:47
Rajaprabhu Aravindasamy
67.2k17 gold badges107 silver badges133 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Bill Criswell
It still needs the
a in the rgba. OP forgot about that.You could do like below:
color = color.replace(/\)/, ', 0.7)')
answered Jun 27, 2014 at 4:53
xdazz
161k38 gold badges255 silver badges278 bronze badges
1 Comment
Frank ZHENG
Yes,I am curious too.What's wrong with this expression?
Similar to above, slightly different method:
var color = 'rgb(148, 141, 124)';
var colorAlpha = color.replace(/rgb/g, 'rgba').replace(/\)/g, ', 0.7)');
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
Justin
I guess I just wanted to temp the mysterious Captain Downvote. Success!
Using .split() also you can easily achieve your goal
var color = 'rgb(148, 141, 124)';
var newColor = color.split(")")[0];
alert(newColor + ', 0.7)');
answered Jun 27, 2014 at 5:02
Sudharsan S
15.4k4 gold badges34 silver badges51 bronze badges
Comments
lang-js
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 from1to.7:) and make sure RGB and RGBA are different only RGB works in some browser but some browser might not work!