How to generate random hex string in javascript

白昼怎懂夜的黑 提交于 2021-01-22 05:16:06

问题


How to generate a random string containing only hex characters (0123456789abcdef) of a given length?


回答1:


Short alternative using spread operator and .map()


Demo 1

const genRanHex = size => [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');

console.log(genRanHex(6));
console.log(genRanHex(12));
console.log(genRanHex(3));

  1. Pass in a number (size) for the length of the returned string.

  2. Define an empty array (result) and an array of strings in the range of [0-9] and [a-f] (hexRef).

  3. On each iteration of a for loop, generate a random number 0 to 15 and use it as the index of the value from the array of strings from step 2 (hexRef) -- then push() the value to the empty array from step 2 (result).

  4. Return the array (result) as a join('')ed string.


Demo 2

const getRanHex = size => {
  let result = [];
  let hexRef = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];

  for (let n = 0; n < size; n++) {
    result.push(hexRef[Math.floor(Math.random() * 16)]);
  }
  return result.join('');
}

console.log(getRanHex(6));
console.log(getRanHex(12));
console.log(getRanHex(3));



回答2:


If you can use lodash library here is the code snippet to generate a 16 chars string:

let randomString = _.times(16, () => (Math.random()*0xF<<0).toString(16)).join('');



回答3:


There are a few ways. One way is to just pull from a predefined string:

function genHexString(len) {
    const hex = '0123456789ABCDEF';
    let output = '';
    for (let i = 0; i < len; ++i) {
        output += hex.charAt(Math.floor(Math.random() * hex.length));
    }
    return output;
}

The other way is to append a random number between 0 and 15 converted to hex with toString:

function genHexString(len) {
    let output = '';
    for (let i = 0; i < len; ++i) {
        output += (Math.floor(Math.random() * 16)).toString(16);
    }
    return output;
}



回答4:


Here's a version that avoids building one digit at a time; it's probably only suitable for short lengths.

function genHexString(len) {
    const str = Math.floor(Math.random() * Math.pow(16, len)).toString(16);
    return "0".repeat(len - str.length) + str;
}


来源:https://stackoverflow.com/questions/58325771/how-to-generate-random-hex-string-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!