generate random strickly 4 character string javascript code example

Example 1: generate random character in javascript

var characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
var result = ""
var chaactersLength = characters.length;

for ( var i = 0; i < 5 ; i++ ) {
    result += characters.charAt(Math.floor(Math.random() * chaactersLength));
}

console.log(result)

Example 2: javascript get random string

function getRandomString(length) {
    var randomChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var result = '';
    for ( var i = 0; i < length; i++ ) {
        result += randomChars.charAt(Math.floor(Math.random() * randomChars.length));
    }
    return result;
}

//usage: getRandomString(20); // pass desired length of random string