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?
random() method is used to generate random characters from the specified characters (A-Z, a-z, 0-9). The for loop is used to loop through the number passed into the generateString() function. During each iteration, a random character is generated.
The quickest way is to use the Math. random() method. The above code will generate a random string of 8 characters that will contain numbers only. To generate an alpha-numeric string, you can pass an integer value between 2 and 36 to the toString() method called radix .
I think this will work for you:
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() *
charactersLength));
}
return result;
}
console.log(makeid(5));
//Can change 7 to 2 for longer results.
let r = (Math.random() + 1).toString(36).substring(7);
console.log("random", r);
Note: The above algorithm has the following weaknesses:
Math.random()
may produce predictable ("random-looking" but not really random) output depending on the implementation. The resulting string is not suitable when you need to guarantee uniqueness or unpredictability.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With