Sunday, September 22, 2024
Google search engine
HomeLanguagesJavascriptHow to convert rgb() color string into an object in JavaScript ?

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen 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!

RELATED ARTICLES

Most Popular

Recent Comments