Random alpha-numeric string in JavaScript? [duplicate]

Random alpha-numeric string in JavaScript? [duplicate]

This question already has an answer here:

Generate random string/characters in JavaScript

65 answers

What’s the shortest way (within reason) to generate a random alpha-numeric (uppercase, lowercase, and numbers) string in JavaScript to use as a probably-unique identifier?


Solution 1:

If you only want to allow specific characters, you could also do it like 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’s a jsfiddle to demonstrate: http://jsfiddle.net/wSQBx/

Another way to do it could be to use a special string that tells the function what types of characters to use. You could do that like 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/

Related:  jQuery Table to CSV export

Alternatively, to use the base36 method as described below you could do something like this:

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

Solution 2:

I just came across this as a really nice and elegant solution:


Notes on this implementation:

  • This will produce a string anywhere between zero and 12 characters long, usually 11 characters, due to the fact that floating point stringification removes trailing zeros.
  • It won’t generate capital letters, only lower-case and numbers.
  • Because the randomness comes from Math.random(), the output may be predictable and therefore not necessarily unique.
  • Even assuming an ideal implementation, the output has at most 52 bits of entropy, which means you can expect a duplicate after around 70M strings generated.

Solution 3:

Another variation of answer suggested by JAR.JAR.beans


By changing multiplicator 1e32 you can change length of random string.

Solution 4:

Or to build upon what Jar Jar suggested, this is what I used on a recent project (to overcome length restrictions):

var randomString = function (len, bits)
    bits = bits || 36;
    var outStr = "", newStr;
    while (outStr.length < len)
        newStr = Math.random().toString(bits).slice(2);
        outStr += newStr.slice(0, Math.min(newStr.length, (len - outStr.length)));
    return outStr.toUpperCase();


randomString(12, 16); // 12 hexadecimal characters
randomString(200); // 200 alphanumeric characters

Solution 5:

One-liner with lodash, for random 20 characters (alphanumeric lowercase):

_.times(20, () => _.random(35).toString(36)).join('');

Solution 6:

This is cleaner

Math.random().toString(36).substr(2, length)


Math.random().toString(36).substr(2, 5)