Reputation: 29
I have an string as below
0.1-rgb(255,112,112)^ 0.2-rgb(255,112,112)^0.5-rgb(270,112,112)-default^1.4-rgb(108,243,1)
I am trying to strip decimal values & strings such as ('-','default','^') so i can get all rgb values in array as below
Expected Result for above ex -
[0]=>rgb(255,112,112)
[1]=>rgb(255,112,112)
[2]=>rgb(108,243,1)
I have tried with .replace(/[0-9].]/g, '') but it replaces numbers in rgb values. pls help.
Upvotes: 1
Views: 37
Reputation: 16
Regex might be the way to go.
var rgbString = "0.1-rgb(255,112,112)^ 0.2-rgb(255,112,112)^0.5-rgb(270,112,112)-default^1.4-rgb(108,243,1)";
const regex = /rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)/gi;
const found = rgbString.match(regex);
console.log(found);
Upvotes: 0
Reputation: 19356
I would turn it inside out and match the rgb(...)
substrings:
let input = "0.1-rgb(255,112,112)^ 0.2-rgb(255,112,112)^0.5-rgb(270,112,112)-default^1.4-rgb(108,243,1)";
let output = input.match(/(rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\))/g);
console.log(output);
The regexp allows spaces either side of individual rgb component values using \s*
.
Upvotes: 1