How to generate a random hexadecimal string in JavaScript

1 Answer

0 votes
function generateHex(length) {
  const hexChars = '0123456789ABCDEF';
  let hexStr = '';

  for (let i = 0; i < length; i++) {
    const index = Math.floor(Math.random() * 16); // Random index from 0 to 15
    hexStr += hexChars[index];
  }

  return hexStr;
}

const length = 8; // Length of the hex string
const hexNumber = generateHex(length);

console.log('Random Hexadecimal Number:', hexNumber);



/*
run:

Random Hexadecimal Number: 77E89729

*/

 



answered Sep 19, 2025 by avibootz

Related questions

...