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 = 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"
}


Contact Us