1

I am trying to load a background color of a clicked box to the array of rgb.

As you can see when I use rgb1 = color.split(",") this creating array of string like

[
  "49",
  " 133",
  " 155"
]

So I tried to parse the items to int like rgb2 = parseInt(color.split(",")); but now I am juts getting 49 on return.

How can I export the result like so?

[49 , 133, 155]

Code:

 $(".box").on("click", function () {

  color = $(this).css("background-color").substring(4).slice(0,-1);

  rgb1 = color.split(",");
  rgb2 = parseInt(color.split(","));
  
  console.log(color);
  console.log(rgb1);
  console.log(rgb2);
  
});
.box{
    height:30px;
    width:30px;
    background:#31859B;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>
halfer
  • 19,824
  • 17
  • 99
  • 186
Behseini
  • 6,066
  • 23
  • 78
  • 125
  • See https://stackoverflow.com/questions/10970958/get-a-color-component-from-an-rgb-string-in-javascript – le_m Jun 23 '17 at 17:12
  • 1
    parseInt(["49","133","155"]) will try to build a string out of that array, so it will do parseInt("49,133,155"), which is then parsed to 49 – Jonas Wilms Jun 23 '17 at 17:14

2 Answers2

3

You could use a regular expression which matches only the number parts. Then convert the strings to number.

var color = "49, 133, 155",
    parts = color.match(/\d+/g).map(Number);

console.log(parts);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

$(".box").on("click", function () {

  color = $(this).css("background-color").substring(4).slice(0,-1);

  rgb1 = color.split(",");
  rgb2 = [];

  for (var i = 0; i < rgb1.length; i++) {
    rgb2[i] = parseInt(rgb1[i]);
  }
  console.log(rgb2);
  
});
.box{
    height:30px;
    width:30px;
    background:#31859B;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>
DonovanM
  • 1,174
  • 1
  • 12
  • 17