1

The following string has been retrieved from an element's style attribute, the attribute is a variable and can contain different colors in a particular vertical gradient background:

string = "background: linear-gradient(0deg, rgb(100, 106, 237) 0%, rgb(101, 222, 108) 100%) repeat scroll 0% 0% transparent; display: list-item; cursor: pointer;"

Using the following code, the linear-gradient contents is extracted from the string:

string = string.substring(string.indexOf('linear-gradient('), 1+string.lastIndexOf(')')); // string = "linear-gradient(0deg, rgb(100, 106, 237) 0%, rgb(101, 222, 108) 100%)"

Now using a regular expression -or any other method- I need to extract both the first rgb -rgb(100, 106, 237)- value as-well as the second -rgb(101, 222, 108). Can anyone please recommend/suggest a simple method to achieve this. Thanks in advance.

3 Answers 3

2

You can use this regular expression to extract all rgb codes:

var regex = /rgb\(([^\)]+)\)/g;
Sign up to request clarification or add additional context in comments.

Comments

1

You can use this:

string.replace(/^.*?linear-gradient *\((.+)/, function($1, $2) {
                         return $1.match(/rgb *\([^)]+\)/g); } );
//=> rgb(100, 106, 237),rgb(101, 222, 108)

Assuming there is no other rgb segment outside closing bracket of linear-gradient

2 Comments

what if there was a mix of rgb & rgba ?
Then use rgba? in regex
1

There is no need for your first extracting. Try the following:

var re = /rgb\(\d{1,3}, ?\d{1,3}, ?\d{1,3}\)/g;

// and then get array of matches

var rgbs = string.match(re);

//It will be equal to null if there is no matches.

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.