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:
JavaScript
x
13
13
1
function makeid(length) {
2
let result = '';
3
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
4
const charactersLength = characters.length;
5
let counter = 0;
6
while (counter < length) {
7
result += characters.charAt(Math.floor(Math.random() * charactersLength));
8
counter += 1;
9
}
10
return result;
11
}
12
13
console.log(makeid(5));