I want to generate a random string that has to have 5 letters from a-z and 3 numbers.
How can I do this with JavaScript?
I\'ve got the following script, but
For someone who is looking for a simplest script. No while (true), no if/else, no declaration.
Base on mwag's answer, but this one uses crypto.getRandomValues, a stronger random than Math.random.
Array(20)
.fill('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$')
.map(x => x[Math.floor(crypto.getRandomValues(new Uint32Array(1))[0] / (0xffffffff + 1) * x.length)])
.join('');
See this for 0xffffffff.
var generatePassword = (
length = 20,
wishlist = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$"
) => Array(length)
.fill('')
.map(() => wishlist[Math.floor(crypto.getRandomValues(new Uint32Array(1))[0] / (0xffffffff + 1) * wishlist.length)])
.join('');
console.log(generatePassword());
var generatePassword = (
length = 20,
wishlist = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$'
) =>
Array.from(crypto.getRandomValues(new Uint32Array(length)))
.map((x) => wishlist[x % wishlist.length])
.join('')
console.log(generatePassword())
const crypto = require('crypto')
const generatePassword = (
length = 20,
wishlist = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$'
) =>
Array.from(crypto.randomFillSync(new Uint32Array(length)))
.map((x) => wishlist[x % wishlist.length])
.join('')
console.log(generatePassword())