I want a 5 character string composed of characters picked randomly from the set [a-zA-Z0-9]
.
What’s the best way to do this with JavaScript?
Advertisement
Answer
I think this will work for you:
function makeid(length) { let result = ''; const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const charactersLength = characters.length; let counter = 0; while (counter < length) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); counter += 1; } return result; } console.log(makeid(5));