How to generate a random alphanumeric string in JavaScript?
P粉775788723
P粉775788723 2023-10-12 23:03:12
0
2
709

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粉775788723
P粉775788723

reply all(2)
P粉312195700

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.
P粉985686557

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);
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template