Convert a linear gradient into an object

Can someone help me convert the linear-gradient value into an object with keys and values?

Here is the initial value:

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

I would like it to be structured like this:

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

UPDATE: Unfortunately, my attempt at coding did not work as expected:

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

Answer №1

Utilizing the power of Regular Expressions, we can precisely specify which sections we want from a given string.

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

// Extract the content between the first ( and last )
str = str.substring(str.indexOf('(') + 1, str.lastIndexOf(')'));

// Finally, by using regex, we can isolate each section individually 
console.log( str.split( /,(?![^(]*\))(?![^"']*["'](?:[^"']*["'][^"']*["'])*[^"']*$)/ ) );

The resulting output will be:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using JavaScript to grab an entire div containing an SVG element

I am looking to capture an entire div as an image and save it locally as proof. Despite reading numerous articles on converting SVG to image or div to image, I have encountered challenges in achieving the desired result. Several attempts with JavaScript l ...

JavaScript, create a loop that waits for a change in value

I've been attempting to ensure that an API is fully loaded before proceeding, but the test code below doesn't seem to be properly implementing the timeout delay. As a result, it seems to be running through the loop too quickly. var google = fals ...

Issue with X overflow visible at the right edge of the webpage (Vue.js and Tailwind CSS)

RESOLVED There is a strange white overflow on the right side of my responsive website that appears and becomes smaller as I scroll down the page. I can't seem to figure out why this is happening. None of the elements are overflowing into that space. ...

Text-field input experiencing issues with placeholder display

As a beginner in Angular, I may make some mistakes. I created a textField input using a directive in Angular: .directive('textField', function () { return { restrict: 'E', scope: true, require: 'ngModel ...

What are some techniques for transforming text into JSON format?

Beginner inquiry: I'm struggling with manipulating text using JavaScript. Here is the text I want to transform: "5555 55:55: John: New York 6666 66:66: Jack: Los Angeles" My desired output after manipulation: [{ name:"John", address:"New York", n ...

CSS Grid expands the item width on its own when there is still space left

Having some queries regarding the piece of code provided. Currently, I have a collection of 5 cards displayed in rows of 3 cards each using the styling grid-template-columns: repeat(3, minmax(200px, 1fr));. My concern is whether there is a way for the 4th ...

How to retrieve the third party child component within a Vue parent component

Within my example-component, I have integrated a third-party media upload child component called media-uploader: <example-component> <form :action= "something"> // Other input types <media-upload :ref="'cover_up ...

Is there a way to enable scanned data to be automatically inputted into a field without manual entry?

I am in the process of creating a user-friendly Android app for virtual inventory management. I want the application to streamline data input by automatically populating text fields upon scanning, eliminating the need for users to manually click on each fi ...

Karma is unable to locate the module within the specified relative path

I'm facing a challenge with Karma not being able to load a specific file. As a novice in Karma, I dedicated the entire day to researching and checking documentation for similar issues with no luck. Upon initiating the karma process, it encounters an ...

Experience the click action that comes equipped with two unique functions: the ability to effortlessly add or remove a class

Currently, I am in the process of creating a list of anchor links that contain nested anchor links, and there are a few functionalities that I am looking to implement. Upon clicking on a link: Add a class of "current" Remove the class of "current" from ...

JSON Novice - persistently storing data in JSON during browser refreshes

My AJAX poll was set up following a guide found here: http://www.w3schools.com/php/php_ajax_poll.asp Instead of storing the poll entries from an HTML radio button in an array within a text file as demonstrated in the tutorial, I wanted to save them in a J ...

Pass data between JavaScript and PHP using the Phaser framework

I am trying to pass a JavaScript variable to PHP and then store it in a database. Despite searching for solutions on Google, I have not been successful. Most suggestions involve using AJAX, but the code doesn't seem to work when I try it. I attempted ...

The error callback encountered {"readyState":4,"status":200,"statusText":"success"} while processing

When I make a call to this url, the response is a JSON object when done directly in the browser. However, when I try to do it via ajax using the following code snippet: $.ajax({ url: url, type: "GET", dataType:"jsonp", succ ...

Combining and serializing a JavaScript object

Combining nested JavaScript objects was straightforward when dealing with a single object. However, as the number of objects has increased, I require a more dynamic approach to merge the address key and serialize my object. var old = {account: "100000 ...

Introducing a script tag using ngBindHtml functionality

My current dilemma involves utilizing external API data that consists of user generated content. My client's request is to dynamically update their website with this feed, while also allowing the use of JavaScript. <div ng-bind-html="post.content" ...

Despite seeming false, my Javascript if statement still evaluates to true

On my webpage, I have a button and a form. The intended functionality is for the button to display the form when clicked, and hide it when clicked again. The issue I'm facing is that no matter if the statement is true or false, the first if statement ...

Using Angular select asynchronously within a custom directive

Despite my efforts, I am struggling to get an angular select with async to work properly. It seems to be mostly working, but not entirely. Consider the controller below: $scope.stuff = {}; $scope.stuff.blah = "SOME_KEY"; External.list().then( function ...

Is there a way to iterate through indexed variables in javascript?

After receiving an array of data from a JQuery .ajax function, I noticed that the fields in the array are named and numbered like part1, part2, part3, etc. I attempted to loop through this data using the code below, but unfortunately, it resulted in NaN: ...

A glitch occurred while attempting to load content dynamically onto an HTML page using Ajax

Attempting to dynamically load content into an HTML div is causing issues for me. Whenever I try to do so, an error pops up: Syntax error HOME. (this is the expected visible content within the div). HTML: Navigation bar: <li><a href="#" onclick= ...

Reasons Behind Slow Unmounting of React Components

In my current project, I have implemented a component that wraps multiple ReactList components. The ReactList component features infinite scrolling, meaning it only loads what is currently in the viewport. There are two modes available - simple and uniform ...