MBehtemam
MBehtemam

Reputation: 7919

Extract RGB and RGBA from css Rules in JavaScript

I have some string like below :

"linear-gradient(to bottom,rgba(255,0,0,0.4) 0,rgba(0,230,175,0.4) 100%);"

i want to extract all rgba and rgb from this stirng like rgba(255,0,0,0.4) and rgba(0,230,175,0.4) . it try to search and find some question like this and this but that answer doesn't help me.

Upvotes: 0

Views: 1364

Answers (2)

Braj
Braj

Reputation: 46841

I want to extract all rgba and rgb from the stirng

I hope you don't want to validate the digits in rgba and rgb, if yes then get the matched group from index 1 using capturing groups.

(rgba?\((?:\d{1,3}[,\)]){3}(?:\d+\.\d+\))?)

Live demo


You can get the values using Lazy way as well in the same way from matched group index 1.

(rgba?.*?\))

Live Demo

Last Pattern explanation:

  (                        group and capture to \1:
    rgb                      'rgb'
    a?                       'a' (optional)
    .*?                      any character except \n (0 or more times)
    \)                       ')'
  )                        end of \1

Upvotes: 3

zx81
zx81

Reputation: 41838

If you just want to match the strings, for instance rgba(255,0,0,0.4), without parsing the values, just use:

arrayOfMatches = yourString.match(/rgba\([^)]+\)/g);

Upvotes: 1

Related Questions