将线性渐变分割为对象

时间:2017-12-13 06:00:10

标签: javascript css object split linear-gradients

我想将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 );

1 个答案:

答案 0 :(得分:1)

使用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"