javascriptstringrandom

Generate a string of random characters


I want a string of fixed length, composed of characters picked randomly from a set of characters e.g. [a-zA-Z0-9].

How can I do this with JavaScript?


Solution

  • 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));