In this tutorial, we will see a JavaScript function to generate a random hex string.
Hexadecimal known as Hex in short is a number system that is composed of 16 units of numbers from 0 to 9 and alphabets A, B, C, D, E, F. The alphabet can be case-insensitive.
To generate a random string of the provided length. We will form an array of these 16 units of numbers and alphabets and then for the asked size, we will run a loop and randomly pick a number from the units array and push them into the result array.
At the end concatenate the characters of the result array and return them as a string.
const randomHexString = length => { let result = []; let hexRef = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; // for the given length for (let n = 0; n < length; n++) { // pick a random unit and store it in result result.push(hexRef[Math.floor(Math.random() * 16)]); } // return the result as a string return result.join(''); } console.log(getRanHex(6)); //"96a1e2" console.log(getRanHex(12)); //"90a2c73c7157" console.log(getRanHex(3)); //"b18"