Home  >  Q&A  >  body text

How to generate a random alphanumeric string in JavaScript?

What is the shortest way (within reason) to generate a random alphanumeric (uppercase, lowercase and numeric) string to use as a possible unique identifier in JavaScript?

P粉775788723P粉775788723373 days ago672

reply all(2)I'll reply

  • P粉312195700

    P粉3121957002023-10-13 12:38:49

    I just discovered this is a very nice and elegant solution:

    Math.random().toString(36).slice(2)

    Comments for this implementation:

    • This will produce a string between 0 and 12 characters in length, typically 11 characters since floating point stringification removes trailing zeros.
    • It will not generate uppercase letters, only lowercase letters and numbers.
    • Since the randomness comes from Math.random(), the output may be predictable and therefore not necessarily unique.
    • Even assuming an ideal implementation, the output will have at most 52 bits of entropy, which means you may end up with duplicates after generating ~70M strings.

    reply
    0
  • P粉985686557

    P粉9856865572023-10-13 09:56:40

    If you only want to allow specific characters, you can also do this:

    function randomString(length, chars) {
        var result = '';
        for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
        return result;
    }
    var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');

    Here is a jsfiddle to demonstrate: http://jsfiddle.net/wSQBx/

    Another approach is to use a special string to tell the function what type of characters to use. You can do this:

    function randomString(length, chars) {
        var mask = '';
        if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
        if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        if (chars.indexOf('#') > -1) mask += '0123456789';
        if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\';
        var result = '';
        for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
        return result;
    }
    
    console.log(randomString(16, 'aA'));
    console.log(randomString(32, '#aA'));
    console.log(randomString(64, '#A!'));

    Fiddle: http://jsfiddle.net/wSQBx/2/

    Alternatively, to use the base36 method described below, you can do the following:

    function randomString(length) {
        return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
    }

    reply
    0
  • Cancelreply