【问题标题】:Parse gradient string into colors将渐变字符串解析为颜色
【发布时间】:2021-11-16 00:23:17
【问题描述】:

我有这些字符串

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))

除了 90 度,也可以是径向的,但我的问题是如何从这些字符串中只获取颜色,以便输出为

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

当没有 hex 和 2x rgba 时,我设法用 .match(/rgba\(.*?\)/g) 做到这一点,但我该怎么做,哪里有 hex 和 rgba,有不透明度的 hex 和 hex 等等?

【问题讨论】:

  • 你试过.match(/rgba\(.*?\)|#\w+/g)吗?
  • @WiktorStribiżew 谢谢你,它很有效

标签: javascript regex string gradient


【解决方案1】:

你可以使用

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

请参阅regex demo详情

  • rgba\([^()]*\) - rgba( 子字符串,然后是除 () 之外的零个或多个字符,然后是 ) 字符
  • | - 或
  • #\w+ - 一个 # 字符,然后是一个或多个字母、数字或 _。您也可以在此处使用“十六进制”字符模式 #[a-fA-F0-9]+

查看 JavaScript 演示:

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))
}

【讨论】:

    猜你喜欢
    • 2019-06-09
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    • 2022-12-21
    • 1970-01-01
    相关资源
    最近更新 更多