Random alpha-numeric string in JavaScript?

JavascriptRandom

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

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

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 2 - Javascript

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/

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 3 - Javascript

UPDATED: One-liner solution, for random 20 characters (alphanumeric lowercase):

Array.from(Array(20), () => Math.floor(Math.random() * 36).toString(36)).join('');

Or shorter with lodash:

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

Solution 4 - Javascript

Another variation of answer suggested by JAR.JAR.beans

(Math.random()*1e32).toString(36)

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

Solution 5 - Javascript

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();
};

Use:

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

Solution 6 - Javascript

This is cleaner

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

Example

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

Solution 7 - Javascript

I think the following is the simplest solution which allows for a given length:

Array(myLength).fill(0).map(x => Math.random().toString(36).charAt(2)).join('')

It depends on the arrow function syntax.

Solution 8 - Javascript

function randomString(len) {
    var p = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    return [...Array(len)].reduce(a=>a+p[~~(Math.random()*p.length)],'');
}

Summary:

> 1. Create an array of the size we want (because there's no range(len) equivalent in javascript. > 2. For each element in the array: pick a random character from p and add it to a string

  1. Return the generated string.

Some explanation:

[...Array(len)]

Array(len) or new Array(len) creates an array with undefined pointer(s). One-liners are going to be harder to pull off. The Spread syntax conveniently defines the pointers (now they point to undefined objects!).

.reduce(

Reduce the array to, in this case, a single string. The reduce functionality is common in most languages and worth learning.

a=>a+...

We're using an arrow function.

a is the accumulator. In this case it's the end-result string we're going to return when we're done (you know it's a string because the second argument to the reduce function, the initialValue is an empty string: ''). So basically: convert each element in the array with p[~~(Math.random()*p.length)], append the result to the a string and give me a when you're done.

p[...]

p is the string of characters we're selecting from. You can access chars in a string like an index (E.g., "abcdefg"[3] gives us "d")

~~(Math.random()*p.length)

Math.random() returns a floating point between [0, 1) Math.floor(Math.random()*max) is the de facto standard for getting a random integer in javascript. ~ is the bitwise NOT operator in javascript. ~~ is a shorter, arguably sometimes faster, and definitely funner way to say Math.floor( Here's some info

Solution 9 - Javascript

for 32 characters:

for(var c = ''; c.length < 32;) c += Math.random().toString(36).substr(2, 1)

Solution 10 - Javascript

Using lodash:

function createRandomString(length) {
        var chars = "abcdefghijklmnopqrstufwxyzABCDEFGHIJKLMNOPQRSTUFWXYZ1234567890"
        var pwd = _.sampleSize(chars, length || 12)  // lodash v4: use _.sampleSize
        return pwd.join("")
    }
document.write(createRandomString(8))

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Solution 11 - Javascript

Random character:

String.fromCharCode(i); //where is an int

Random int:

Math.floor(Math.random()*100);

Put it all together:

function randomNum(hi){
    return Math.floor(Math.random()*hi);
} 
function randomChar(){
    return String.fromCharCode(randomNum(100));
}
function randomString(length){
   var str = "";
   for(var i = 0; i < length; ++i){
        str += randomChar();
   }
   return str;
}
var RandomString = randomString(32); //32 length string

Fiddle: http://jsfiddle.net/maniator/QZ9J2/

Solution 12 - Javascript

Random Key Generator

keyLength argument is the character length you want for the key

function keyGen(keyLength) {
    var i, key = "", characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    var charactersLength = characters.length;
    
    for (i = 0; i < keyLength; i++) {
        key += characters.substr(Math.floor((Math.random() * charactersLength) + 1), 1);
    }

    return key;
}


keyGen(12)
"QEt9mYBiTpYD"

Solution 13 - Javascript

var randomString = function(length) {
  var str = '';
  var chars ='0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split(
      '');
  var charsLen = chars.length;
  if (!length) {
    length = ~~(Math.random() * charsLen);
  }
  for (var i = 0; i < length; i++) {
    str += chars[~~(Math.random() * charsLen)];
  }
  return str;
};

Solution 14 - Javascript

When I saw this question I thought of when I had to generate UUIDs. I can't take credit for the code, as I am sure I found it here on stackoverflow. If you dont want the dashes in your string then take out the dashes. Here is the function:

function generateUUID() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(c) {
        var r = (d + Math.random()*16)%16 | 0;
        d = Math.floor(d/16);
        return (c=='x' ? r : (r&0x7|0x8)).toString(16);
    });
    return uuid.toUpperCase();
}

Fiddle: http://jsfiddle.net/nlviands/fNPvf/11227/

Solution 15 - Javascript

This function should give a random string in any length.

function randString(length) {
    var l = length > 25 ? 25 : length;
    var str = Math.random().toString(36).substr(2, l);
    if(str.length >= length){
        return str;
    }
    return str.concat(this.randString(length - str.length));
}

I've tested it with the following test that succeeded.

function test(){
    for(var x = 0; x < 300000; x++){
        if(randString(x).length != x){
            throw new Error('invalid result for len ' + x);
        }
    }
}

The reason i have chosen 25 is since that in practice the length of the string returned from Math.random().toString(36).substr(2, 25) has length 25. This number can be changed as you wish.

This function is recursive and hence calling the function with very large values can result with Maximum call stack size exceeded. From my testing i was able to get string in the length of 300,000 characters.

This function can be converted to a tail recursion by sending the string to the function as a second parameter. I'm not sure if JS uses Tail call optimization

Solution 16 - Javascript

Nice and simple, and not limited to a certain number of characters:

let len = 20, str = "";
while(str.length < len) str += Math.random().toString(36).substr(2);
str = str.substr(0, len);

Solution 17 - Javascript

Here's a simple code to generate random string alphabet. Have a look how this code works.

go(lenthOfStringToPrint); - Use this function to generate the final string.

var letters = {
  1: ["q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m"],
  2: ["Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M"]
},i,letter,final="";
random = (max,min) => {
  return Math.floor(Math.random()*(max-min+1)+min);
}
function go(length) {
  final="",letter="";
  for (i=1; i<=length; i++){
    letter = letters[random(0,3)][random(0,25)];
    final+=letter;
  }
  return final;
}

Solution 18 - Javascript

One could just use lodash uniqueId:

    _.uniqueId([prefix=''])

> Generates a unique ID. If prefix is given, the ID is appended to it.

Solution 19 - Javascript

Use md5 library: https://github.com/blueimp/JavaScript-MD5

The shortest way:

md5(Math.random())

If you want to limit the size to 5:

md5(Math.random()).substr(0, 5)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPavelView Question on Stackoverflow
Solution 1 - JavascriptJAR.JAR.beansView Answer on Stackoverflow
Solution 2 - JavascriptNimphiousView Answer on Stackoverflow
Solution 3 - JavascriptDS.View Answer on Stackoverflow
Solution 4 - Javascripthe-yaehView Answer on Stackoverflow
Solution 5 - JavascriptJosh McView Answer on Stackoverflow
Solution 6 - JavascriptDiego MelloView Answer on Stackoverflow
Solution 7 - JavascriptLászló MondaView Answer on Stackoverflow
Solution 8 - JavascriptroundarView Answer on Stackoverflow
Solution 9 - JavascriptCollin AndersonView Answer on Stackoverflow
Solution 10 - JavascriptalexloehrView Answer on Stackoverflow
Solution 11 - JavascriptNaftaliView Answer on Stackoverflow
Solution 12 - JavascriptseaBassView Answer on Stackoverflow
Solution 13 - JavascriptJoey DiasView Answer on Stackoverflow
Solution 14 - JavascriptnlvView Answer on Stackoverflow
Solution 15 - JavascriptYaki KleinView Answer on Stackoverflow
Solution 16 - Javascriptuser993683View Answer on Stackoverflow
Solution 17 - JavascriptNeutral MeView Answer on Stackoverflow
Solution 18 - JavascriptAdrianView Answer on Stackoverflow
Solution 19 - JavascriptJorge AlbertoView Answer on Stackoverflow