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

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 = newObject();  Â// 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> functionrgbToObj(rgb) {  Â    let colors = ["red", "green", "blue", "alpha"]  Â    let colorArr = rgb.slice(         rgb.indexOf("(") + 1,          rgb.indexOf(")")     ).split(", ");  Â    let obj = newObject();  Â    colorArr.forEach((k, i) => {         obj[colors[i]] = k     })  Â    returnobj; }  Â Â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"
}
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
 
				 
					


