1

I want to generate a random alpha-numeric string in JavaScript, with a-z, A-Z, or 0-9.

This is the function I came up with. It is not very efficient computing but it gets the job done for small strings. Is there a less computationally demanding way?

function AlphaNumericString(length) {
    let a = ''
    for (let i = 0; i < length; i++) {
        let tmp = Math.floor(Math.random() * 3) //randomly pick which type of char
        switch (tmp) {
            // numbers 0-9
            case 0:
                a = a + String.fromCharCode(Math.floor(Math.random() * 10 + 48));
                break;
            // uppercase letters
            case 1:
                a = a + String.fromCharCode(Math.floor(Math.random() * 26 + 65));
                break;
            //  lowercase letters
            case 2:
                a = a + String.fromCharCode(Math.floor(Math.random() * 26 + 97));
                break;
        }
    }
    return a;
}
STEVE J
  • 21
  • 3

0 Answers0