3

according to one of StackOverflow topics I tried to create own RGB to HEX colors converter.

I don't know why but instead converting it double RGB numbers.

So when input is rgb(0, 128, 192) it console out #00128192.

My code is:

fromRGB: {
    toHEX: {
        supportFunc: function(number) {
            var hex = number.toString(16);
            return hex.length == 1 ? '0' + hex : hex;
        },
        convert: function(r, g, b) {
            var lol = '#' + this.supportFunc(r) + this.supportFunc(g) + this.supportFunc(b);
            console.log(lol);
        }
    },
    prepareAndExecute: function(color_field) {
        // preparing
        var numbers = color_field.match(/\d+/g);
        if(numbers.length == 3) {
            this.toHEX.convert(numbers[0], numbers[1], numbers[2]);
        } else {
            alert('wrong RGB number format');
        }


        //this.toHSL(preparedValue);
    }
}

I execute prepare function, lol variable is the one that should contains converted color in HEX format.

What is wrong with my code, why it doesn't work?

BT101
  • 3,666
  • 10
  • 41
  • 90
  • 1
    `.match()` returns an array of **strings**, not numbers. – Pointy Sep 16 '17 at 15:49
  • Possible duplicate of [RGB to Hex and Hex to RGB](https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb) – Ken White Sep 16 '17 at 15:57
  • @KenWhite I think OP already used that duplicate link to come up with his code above. But he encountered a problem (strings as numbers) that is not related to how to get the values. Thus marking it as duplicate to that link is wrong. – ibrahim mahrir Sep 16 '17 at 15:59
  • @ibrahimmahrir: Then the poster didn't properly use the code from the linked post and should go back and read it again. It's still a duplicate of the basic question, which is *Converting RGB to HEX in Javascript*. – Ken White Sep 16 '17 at 16:20
  • Possible duplicate of [Convert rgb strings to hex in Javascript](https://stackoverflow.com/questions/13070054/convert-rgb-strings-to-hex-in-javascript) – Slai Sep 16 '17 at 20:27

1 Answers1

1

Explanation:

It's because you're passing strings not numbers to supportFunc.

The result of match in prepareAndExecute is an array of strings, thus when you call toString in supportFunc, you are calling String.prototype.toString (not Number.prototype.toString) which return the string as is.

Solution:

In supportFunc, convert number to a number before using toString:

var hex = Number(number).toString(16);                       // using Number to convert a string to a number (you can use parseInt or unary + if you like)

or convert them before passing them to convert:

this.toHEX.convert(+numbers[0], +numbers[1], +numbers[2]);   // using unary +
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73