Reputation: 474
I would highly appreciate it if someone can point me in the right direction on this. I have an array "cArr" and within this array I have 2 elements. What I would like to do is to match the "rgb(xx,xx,xx)"and push it to an array "rgbArr"; The issue that I am encountering is with regEx.
Here is my code:
var cArr = ["id0{shape:round,rgb(24,23,12)}","id1{shape:long,weight:heavy,rgb(20,20,20)}","id2{shape:elongated,weigth:light,rgb(15,24,8)}"];
for(var i=cArr.length -1; i>=0; i--)
{
if(cArr[i].match(matchColors))
{
rgbArr.push(cArr[i]);
break;
}
}
console.log(rgbArr);
Upvotes: 0
Views: 658
Reputation: 116
I was wrestling with this issue today and have a slightly more simplified solution to this issue which uses a slightly different Regular Expression along with JavaScripts 'match' function (I have wrapped it up in a function so that we can reuse this functionality as required):
function parseRGB ( string ) {
var rgbRegex = /(rgb\([^)]*\))/gi;
var rgbArray = string.match(rgbRegex);
return rgbArray;
}
Now simply call the function with the value you want to check. E.g.
parseRGB( '-moz-linear-gradient( top, rgb(68, 68, 68), rgb(153, 153, 153))' );
Which will return the following array:
[ "rgb(68, 68, 68)", "rgb(153, 153, 153)" ]
A few things to note:
Hope this helps someone.
Upvotes: 2
Reputation: 19237
Please clarify your question (seem my comment above), for the time being try something like this. (But this doesn't give you the multiple rgb colors in the 1st element...)
var matchColors=/.*?(rgb\([^)]*\)).*/;
var cArr = ["id0{shape:round,rgb(24,23,12)},id1{shape:long,weight:heavy,rgb(20,20,20)}","id2{shape:elongated,weigth:light,rgb(15,24,8)}","sdf"];
var rgbArr=[];
for(var i=cArr.length -1; i>=0; i--) {
if(cArr[i].match(matchColors)) {
var x = cArr[i].replace(matchColors,"$1");
rgbArr.push(x);
// break;
}
}
console.log(rgbArr);
Upvotes: 1