Janes Janes - 2 months ago 12
Javascript Question

Generate string/characters in JavaScript

Now, I want to set the output generated in constant( first two in letters,last three in numeric).
What code should I use? Thanks.

Javascript

function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));

return text;
}
console.log(makeid());

Answer Source

You could try separating your 'possible' string into possibleNums and possibleChars

var possibleNums = "0123456789";
var possibleAlpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

for (var i = 0; i < 2; i++) {
    text += possibleAlpha.charAt(Math.floor(Math.random() * possibleAlpha.length));
}

for (var i = 0; i < 3; i++) {
    text += possibleNums.charAt(Math.floor(Math.random() * possibleNums.length));
}