Sometimes, we want to format hexadecimal number to short UUID in JavaScript.
In this article, we’ll look at how to format hexadecimal number to short UUID in JavaScript.
How to format hexadecimal number to short UUID in JavaScript?
To format hexadecimal number to short UUID in JavaScript, we can use some JavaScript string methods.
For instance, we write:
const toPaddedHexString = (num, len) => {
const str = num.toString(16);
return "0".repeat(len - str.length) + str;
}
const hexStr = toPaddedHexString(12345, 16);
const result = hexStr.substr(0, 8) + '-' + hexStr.substr(8, 4) + '-' + hexStr.substr(12, 4);
console.log(result)
We create the toPaddedHexString
function to convert num
to a hex number.
Then we return the str
string padded to len
characters with "0".repeat(len - str.length) + str
.
Then we call toPaddedHexString
with 12345 and 16 to return 12345 converted to hex and padded to 16 characters.
Finally, we add the dashes between the digit groups by calling hex.substr
with the start and end indexes of each segment and adding dashes between between them.
Therefore, result
is '00000000-0000-3039'
.
Conclusion
To format hexadecimal number to short UUID in JavaScript, we can use some JavaScript string methods.