Search code examples
javascriptregexstringgradient

Parse gradient string into colors


I have these strings

linear-gradient(90deg, rgba(196,97,97,1), #222222)
linear-gradient(90deg, #222222, #222222)
linear-gradient(90deg, #222, #22222280)
linear-gradient(90deg, rgba(196,97,97,1), rgba(196,97,97,1))

Instead 90deg, there can also be radial, but my question is how can I get only colors from these string so the output would be

[rgba(196,97,97,1), #222222]
[#222222, #222222]
[#222, #22222280]
[rgba(196,97,97,1), rgba(196,97,97,1)]

When the are no hex and 2x rgba I managed to do it with .match(/rgba\(.*?\)/g) but how do I do it, where there are hex and rgba, hex and hex with opacity etc?


Solution

  • You can use

    .match(/rgba\([^()]*\)|#\w+/g)
    

    See the regex demo. Details:

    • rgba\([^()]*\) - rgba( substring, then zero or more chars other than ( and ) and then a ) char
    • | - or
    • #\w+ - a # char and then one or more letters, digits or _. You may also use the "hex" chars pattern here, #[a-fA-F0-9]+.

    See the JavaScript demo:

    const texts = ['linear-gradient(90deg, rgba(196,97,97,1), #222222)',
    'linear-gradient(90deg, #222222, #222222)',
    'linear-gradient(90deg, #222, #22222280)',
    'linear-gradient(90deg, rgba(196,97,97,1), rgba(196,97,97,1))'];
    for (const text of texts) {
      console.log(text, '->', text.match(/rgba\([^()]*\)|#\w+/g))
    }