Sometimes, we want to generate random hex string in JavaScript.
In this article, we’ll look at how to generate random hex string in JavaScript.
How to generate random hex string in JavaScript?
To generate random hex string in JavaScript, we can use the Math.random
and toString
methods.
For instance, we write:
const genRanHex = size => [...Array(size)]
.map(() => Math.floor(Math.random() * 16).toString(16)).join('');
console.log(genRanHex(6));
console.log(genRanHex(8));
to define the genRanHex
function to generate the hex number.
In the function, we create an array with the given size
and make a copy of it with [...Array(size)]
.
Then we call map
with a callback that returns the randomly generated hex number with Math.floor(Math.random() * 16).toString(16)
.
We call toString
with 16 to convert the randomly generated decimal number to hex.
Finally, we call join
with an empty string to combine them together.
Conclusion
To generate random hex string in JavaScript, we can use the Math.random
and toString
methods.
2 replies on “How to generate random hex string in JavaScript?”
Thanks friend, very useful snippet for generating IDs.
Thanks for reading