将线性渐变拆分为一个对象

Split linear-gradient into an object

我想将 linear-gradient 值拆分为具有键和值的 object

我有这个:

linear-gradient(10deg,#111,rgba(111,111,11,0.4),rgba(255,255,25,0.1))

我想要这样:

linear-gradient: {
  angle: '10deg',
  color1: '#111',
  color2: 'rgba(111,11,11,0.4)',
  color3: 'rgba(255,255,25,0.1)',
}

已编辑:我尝试了我的代码但没有成功:

var str = 'linear-gradient(10deg,#111,rgba(111,111,11,0.4),rgba(255,255,25,0.1))';
str = str.match("gradient\((.*)\)");
str = str[1].split(',');
console.log( str );

使用Regular expression我们可以定义我们想要的字符串部分。

// Define string
var str = 'linear-gradient(to left top, #F0F calc(30% - 6px), hsl(100, 100%, 25%) 75%, yellow)';

// Get string between first ( and last )
str = str.substring(str.indexOf('(') + 1, str.lastIndexOf(')'));

// Finally with regex we can get each parts separatelly
console.log( str.split( /,(?![^(]*\))(?![^"']*["'](?:[^"']*["'][^"']*["'])*[^"']*$)/ ) );

输出将是:

(4) [Array]
  "to left top"
  "#F0F calc(30% - 6px)"
  "hsl(100, 100%, 25%) 75%"
  "yellow"