Divide linear gradient by object

I want to split the linear-gradient value into object with key and value.

I have it:

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

And I want it to be like this:

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

EDITED: I tried my code without success:

 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 ); 
+5
source share
1 answer

With Regular expression we can determine what parts we want from the string.

 // 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( /,(?![^(]*\))(?![^"']*["'](?:[^"']*["'][^"']*["'])*[^"']*$)/ ) ); 

And the conclusion will be:

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

Source: https://habr.com/ru/post/1274020/


All Articles