Open In App

How to convert rgb() color string into an object in JavaScript ?

Last Updated : 06 Apr, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given a color in the form of rgb( ) or rgba() and the task is to convert it into an object where the keys are the color names and values are the color values.

Example:

Input:    rgb(242, 52, 110)
Output: {
   red: 242,
   green: 52,
   blue: 110
}

Input:    rgba(255, 99, 71, 0.5)
Output: {
  red: 255,
  green: 99,
  blue: 71,
  alpha: 0.5
}

Approach: To achieve this we use the following approach.

  • Store the color in a variable named rgb.
  • Create an array named colors that contain the names of the colors red, green, blue, and alpha.
  • Create a variable names colorArr in which we store the color values of the input rgb. For example: [“255”, “99”, “71”, 0.5], to achieve this we slice the rgb from where the “(“ present to from where the “)” present. Now you got the string “255, 99, 71, 0.5”. Now split the array from where the “, ” present. Now you get the array [“255″, ’99”, “71”, “0.5”].
  • Now create an empty object.
  • Apply forEach loop on the colorArr and for every iteration insert the name of color and value of the color to the object.
  • Now print the object.

Javascript




<script>
let rgb = "rgba(255, 99, 71, 0.5)"
  
let colors = ["red", "green", "blue", "alpha"]
  
// Getting the index of "(" and ")" 
// by using the indexOf() method
let colorArr = rgb.slice(
    rgb.indexOf("(") + 1, 
    rgb.indexOf(")")
).split(", ");
  
let obj = new Object();
  
// Insert the values into obj
colorArr.forEach((k, i) => {
    obj[colors[i]] = k
})
  
console.log(obj)
</script>


Output:

{
  alpha: "0.5",
  blue: "71",
  green: "99",
  red: "255"
}

Wrap the logic inside a function

Javascript




<script>
function rgbToObj(rgb) {
  
    let colors = ["red", "green", "blue", "alpha"]
  
    let colorArr = rgb.slice(
        rgb.indexOf("(") + 1, 
        rgb.indexOf(")")
    ).split(", ");
  
    let obj = new Object();
  
    colorArr.forEach((k, i) => {
        obj[colors[i]] = k
    })
  
    return obj;
}
  
  
console.log(rgbToObj("rgb(255, 99, 71)"))
console.log(rgbToObj("rgb(255, 99, 71, 0.5)"))
</script>


Output:

{
  blue: "71",
  green: "99",
  red: "255"
}

{
  alpha: "0.5",
  blue: "71",
  green: "99",
  red: "255"
}

Master DSA with JavaScript in just 90 days. Explore core DSA concepts, refine your coding skills, and tackle real-world challenges. Take on the Three 90 Challenge—complete 90% of the course in 90 days and earn a 90% refund as a reward for your commitment!


Similar Reads

How to create RGB color generator using HTML CSS and JavaScript ?
In this article, we will create a RGB color generator using HTML, CSS, and JavaScript. Using RGB color generator, we can construct all the colors from the combination of Red, Green, Blue colors. Each color is represented by the range of decimal numbers from 0 to 255 (256 levels for each color). So, the total number of available colors is 256 x 256
3 min read
D3.js | color.rgb() Function
The color.rgb() function in D3.js is used to return the RGB equivalent of the specified color. Syntax: color.rgb() Parameters: This function does not accept any parameters. Return Value: This function returns the RGB equivalent of the specified color. Below programs illustrate the color.rgb() function in D3.js: Example 1: javascript <!DOCTYPE ht
1 min read
Less.js Color Definition rgb() Function
Less.js is a simple CSS pre-processor that facilitates the creation of manageable, customizable, and reusable style sheets for websites. Because CSS uses a dynamic style sheet language, it is more advantageous. LESS is adaptable enough to function in a variety of browsers. A computer language called the CSS pre-processor is used to build and enhanc
3 min read
RGB Color Slider Using React js
In this article, we will create a RGB color slider Using ReactJS. The RGB Color Slider web application offers an interactive way for users to choose and preview colors via red, green, and blue sliders. Among its features, it sports a real-time visualization of the selected color, as well as allows users to copy RGB and HEX color codes, generate ran
4 min read
How to get hex color value of RGB value ?
Given the RGB color value and the task is to get the Hex Code of that color using JavaScript. Approach 1: Call the convert() user-defined function and use RGB value as a parameter.Use the match() method to select the value of Red, Green, and Blue. The value of RGB is stored in the form of array.The hexCode() function call to convert the value of R
2 min read
Difference between RGB vs RGBA color format
In this article, we will discuss the differences between RGB and RGBA color schemes in detail. We will also see how these schemes can be used in CSS. RGB Color Scheme: It is a three-channel format containing data for red, green, and blue colors. In CSS, the RGB color format can be specified using: rgb(red, green, blue) Each parameter in rgb() funct
3 min read
How to convert 3-digit color code to 6-digit color code using JavaScript ?
In this article, we are converting a three-digit color HEX code into a six-digit color HEX code using JavaScript. To solve this problem, first, we copy the individual digits and paste them at the consecutive positions. For example - #34E will be converted into #3344EE and #E90 will be converted into #EE9900. Steps to convert 3-digit color code to 6
2 min read
How to Push an Object into Another Object in JavaScript ?
In JavaScript, the concept of pushing an object into another object involves embedding one object within another as a property. This technique is useful for organizing data structures where related information is grouped, enhancing the ability to manage and manipulate complex data sets effectively.There are several ways to push an object into anoth
4 min read
How to change text color depending on background color using JavaScript?
The task is to set the foreground color based on the background color so that it will become visible. Here few of the important techniques are discussed. We are going to use JavaScript. Approach: First, select the random Background color(by selecting random RGB values) or a specific one.Use the YIQ formula to get the YIQ value.Depending on the YIQ
3 min read
D3.js | d3.rgb() Function
The d3.rgb() function in D3.js is used to return RGB value of the specified CSS color. Syntax: d3.rgb(color); Parameters: This function accepts single parameter color which is used to specify the CSS color. Return Value: This function returns RGB value of the given CSS color. Below programs illustrate the d3.rgb() function in D3.js: Example 1: java
1 min read
  翻译: