David David - 3 months ago 32
Javascript Question

Formatting hexadecimal Number in Javascript

I have a hexadecimal number in javascript. For display purposes, I would like to format the string as:


(8 digits)-(4 digits)-(4 digits) with padded zeros on the front

I've been trying to write my own loop to format an arbitrary hexadecimal number into this format, but this seems like something that should be available in javascript already. Is there a built-in way to format a hexadecimal number in javascript?



I would do a two-step process:

1) convert number to 16 digit hex with leading zeros:

var i = 12345; // your number
var h = ("000000000000000" + i.toString(16)).substr(-16);

2) add dashes

var result = h.substr(0, 8)+'-'+h.substr(8,4)+'-'+h.substr(12,4);