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>

2
  • See stackoverflow.com/questions/10970958/… Commented Jun 23, 2017 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 Commented Jun 23, 2017 at 17:14

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.