1

I want to make random bytes and turn it into hexadecimal.

I had used it earlier in php as the id of a database table.

if in php, the code like this

function rand_id(){
    return bin2hex(random_bytes(3));
}

how to do that in jquery

  • Well, a byte would be something like `a` or `g` or `3` or `{`, so just place those in an array and use Math.random to get a random byte. – adeneo Oct 08 '16 at 18:56
  • [Generate random string/characters in JavaScript](http://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript) – adeneo Oct 08 '16 at 18:57
  • 1
    it's true, but this "��T0)�" what i get in php,, i thonk i'll try your recomend –  Oct 08 '16 at 20:12
  • 1
    See also [Javascript character (ASCII) to Hex](http://stackoverflow.com/questions/20580045/javascript-character-ascii-to-hex) – guest271314 Oct 08 '16 at 20:14

1 Answers1

0
function random_hexadecimal(length) {
    var result = '';
    var characters = 'abcdef0123456789';
    var charactersLength = characters.length;
    for (i = 0; i < length; i++) result += characters.charAt(Math.floor(Math.random() * charactersLength));
    return result;
}

You can use the above

Edit:

If you would like to do this server side, you can use the crypto module

var crypto = require("crypto");
var id = crypto.randomBytes(20).toString('hex');

// "bb5dc8842ca31d4603d6aa11448d1654"

Edit2:

You can also use this: 
var size = 20;
var id = [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');


// "6b6a3edaf6f1cbaaf107"
MartinNajemi
  • 514
  • 3
  • 18
  • Highly inefficient solution. Randomizing per character, which stands for 4 bits, is totally unnecessary. – Jonathan Jacobson Jun 24 '21 at 13:09
  • Flagging your solution as highly inefficient is a positive contribution to whoever reads your advice. But it's not truly your solution, having copied it from https://stackoverflow.com/a/1349426/5524100 (before doing a minor adjustment). – Jonathan Jacobson Jun 24 '21 at 14:52