Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split linear-gradient into an object [duplicate]

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

I have this:

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

And I want it 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 );
like image 719
Behzad Avatar asked Dec 13 '17 06:12

Behzad


People also ask

How do I stop a repeating linear gradient in CSS?

A color-stop's <color> value, followed by one or two optional stop positions, (each being either a <percentage> or a <length> along the gradient's axis). A percentage of 0% , or a length of 0 , represents the start of the gradient; the value 100% is 100% of the image size, meaning the gradient will not repeat.

What is Webkit gradient?

First, -webkit-gradient uses a two-point syntax that lets you explicitly state where a linear gradient starts and ends. linear-gradient does away with this in favor of convenient box-filling behavior. If you really want the gradient to stop before the edges of the box, you can do so via color stop placement.

What is the required number of colors to produce a gradient effect?

To create the most basic type of gradient, all you need is to specify two colors. These are called color stops. You must have at least two, but you can have as many as you want.

How do you apply a linear gradient to text in CSS?

CSS Code: For CSS code, please follow the steps given below. Step 1: Apply a basic background to the body tag and align the text to center of the page. Step 2: Do some basic styling like font-size and family etc. Step 3: Apply the linear gradient property with any colors of your choice.


1 Answers

With Regular expression we can define what parts we want from 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 output will be:

(4) [Array]
  "to left top"
  "#F0F calc(30% - 6px)"
  "hsl(100, 100%, 25%) 75%"
  "yellow"
like image 114
Behzad Avatar answered Nov 15 '22 00:11

Behzad