0

Using JavaScript I am trying to randomly generate a hexadecimal color code:

var color = '#'+(Math.random()*0xFFFFFF<<0).toString(16);

This almost works, but sometimes, if the randomly generated number is too low, the code doesn't put the leading '0' or '00' at the front of the hexadecimal code.

Is there a simple way to fix this?

user1551817
  • 6,693
  • 22
  • 72
  • 109
  • 1
    People usually do `('000000'+hex).slice(-6)` – georg Feb 07 '18 at 18:55
  • Actually, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart, as pointed out in the dupe... – georg Feb 07 '18 at 19:51

2 Answers2

1

var color = (Math.random() * 0xFFFFFF).toString(16);
var hex = "#" + ("000000" + color).substr(-6, 6);
document.write(hex);
lmarqs
  • 1,469
  • 13
  • 16
1

You can add '000000' and slice by six characters from the end of string:

var color = '#' + ('000000' + (Math.random() * 0xFFFFFF << 0).toString(16)).slice(-6);
Dawid Loranc
  • 852
  • 2
  • 9
  • 22