Generate random string/characters in JavaScript

JavascriptStringRandom

Javascript Problem Overview


I want a 5 character string composed of characters picked randomly from the set [a-zA-Z0-9].

What's the best way to do this with JavaScript?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

//Can change 7 to 2 for longer results.
let r = (Math.random() + 1).toString(36).substring(7);
console.log("random", r);

Note: The above algorithm has the following weaknesses:

  • It will generate anywhere between 0 and 6 characters due to the fact that trailing zeros get removed when stringifying floating points.
  • It depends deeply on the algorithm used to stringify floating point numbers, which is horrifically complex. (See the paper "How to Print Floating-Point Numbers Accurately".)
  • Math.random() may produce predictable ("random-looking" but not really random) output depending on the implementation. The resulting string is not suitable when you need to guarantee uniqueness or unpredictability.
  • Even if it produced 6 uniformly random, unpredictable characters, you can expect to see a duplicate after generating only about 50,000 strings, due to the birthday paradox. (sqrt(36^6) = 46656)

Solution 3 - Javascript

Math.random is bad for this kind of thing

Option 1

If you're able to do this server-side, just use the crypto module -

var crypto = require("crypto");
var id = crypto.randomBytes(20).toString('hex');

// "bb5dc8842ca31d4603d6aa11448d1654"

The resulting string will be twice as long as the random bytes you generate; each byte encoded to hex is 2 characters. 20 bytes will be 40 characters of hex.


Option 2

If you have to do this client-side, perhaps try the uuid module -

var uuid = require("uuid");
var id = uuid.v4();

// "110ec58a-a0f2-4ac4-8393-c866d813b8d1"

Option 3

If you have to do this client-side and you don't have to support old browsers, you can do it without dependencies -

// dec2hex :: Integer -> String
// i.e. 0-255 -> '00'-'ff'
function dec2hex (dec) {
  return dec.toString(16).padStart(2, "0")
}

// generateId :: Integer -> String
function generateId (len) {
  var arr = new Uint8Array((len || 40) / 2)
  window.crypto.getRandomValues(arr)
  return Array.from(arr, dec2hex).join('')
}

console.log(generateId())
// "82defcf324571e70b0521d79cce2bf3fffccd69"

console.log(generateId(20))
// "c1a050a4cd1556948d41"


For more information on crypto.getRandomValues -

> The crypto.getRandomValues() method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning).

Here's a little console example -

> var arr = new Uint8Array(4) # make array of 4 bytes (values 0-255)
> arr
Uint8Array(4) [ 0, 0, 0, 0 ]

> window.crypto
Crypto { subtle: SubtleCrypto }

> window.crypto.getRandomValues()
TypeError: Crypto.getRandomValues requires at least 1 argument, but only 0 were passed

> window.crypto.getRandomValues(arr)
Uint8Array(4) [ 235, 229, 94, 228 ]

For IE11 support you can use -

(window.crypto || window.msCrypto).getRandomValues(arr)

For browser coverage see https://caniuse.com/#feat=getrandomvalues

Solution 4 - Javascript

Short, easy and reliable

Returns exactly 5 random characters, as opposed to some of the top rated answers found here.

Math.random().toString(36).slice(2, 7);

Solution 5 - Javascript

Here's an improvement on doubletap's excellent answer. The original has two drawbacks which are addressed here:

First, as others have mentioned, it has a small probability of producing short strings or even an empty string (if the random number is 0), which may break your application. Here is a solution:

(Math.random().toString(36)+'00000000000000000').slice(2, N+2)

Second, both the original and the solution above limit the string size N to 16 characters. The following will return a string of size N for any N (but note that using N > 16 will not increase the randomness or decrease the probability of collisions):

Array(N+1).join((Math.random().toString(36)+'00000000000000000').slice(2, 18)).slice(0, N)

Explanation:

  1. Pick a random number in the range [0,1), i.e. between 0 (inclusive) and 1 (exclusive).
  2. Convert the number to a base-36 string, i.e. using characters 0-9 and a-z.
  3. Pad with zeros (solves the first issue).
  4. Slice off the leading '0.' prefix and extra padding zeros.
  5. Repeat the string enough times to have at least N characters in it (by Joining empty strings with the shorter random string used as the delimiter).
  6. Slice exactly N characters from the string.

Further thoughts:

  • This solution does not use uppercase letters, but in almost all cases (no pun intended) it does not matter.
  • The maximum string length at N = 16 in the original answer is measured in Chrome. In Firefox it's N = 11. But as explained, the second solution is about supporting any requested string length, not about adding randomness, so it doesn't make much of a difference.
  • All returned strings have an equal probability of being returned, at least as far as the results returned by Math.random() are evenly distributed (this is not cryptographic-strength randomness, in any case).
  • Not all possible strings of size N may be returned. In the second solution this is obvious (since the smaller string is simply being duplicated), but also in the original answer this is true since in the conversion to base-36 the last few bits may not be part of the original random bits. Specifically, if you look at the result of Math.random().toString(36), you'll notice the last character is not evenly distributed. Again, in almost all cases it does not matter, but we slice the final string from the beginning rather than the end of the random string so that short strings (e.g. N=1) aren't affected.

Update:

Here are a couple other functional-style one-liners I came up with. They differ from the solution above in that:

  • They use an explicit arbitrary alphabet (more generic, and suitable to the original question which asked for both uppercase and lowercase letters).
  • All strings of length N have an equal probability of being returned (i.e. strings contain no repetitions).
  • They are based on a map function, rather than the toString(36) trick, which makes them more straightforward and easy to understand.

So, say your alphabet of choice is

var s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

Then these two are equivalent to each other, so you can pick whichever is more intuitive to you:

Array(N).join().split(',').map(function() { return s.charAt(Math.floor(Math.random() * s.length)); }).join('');

and

Array.apply(null, Array(N)).map(function() { return s.charAt(Math.floor(Math.random() * s.length)); }).join('');

Edit:

I seems like qubyte and Martijn de Milliano came up with solutions similar to the latter (kudos!), which I somehow missed. Since they don't look as short at a glance, I'll leave it here anyway in case someone really wants a one-liner :-)

Also, replaced 'new Array' with 'Array' in all solutions to shave off a few more bytes.

Solution 6 - Javascript

The most compact solution, because slice is shorter than substring. Subtracting from the end of the string allows to avoid floating point symbol generated by the random function:

Math.random().toString(36).slice(-5);

or even

(+new Date).toString(36).slice(-5);

Update: Added one more approach using btoa method:

btoa(Math.random()).slice(0, 5);
btoa(+new Date).slice(-7, -2);
btoa(+new Date).substr(-7, 5);

// Using Math.random and Base 36:
console.log(Math.random().toString(36).slice(-5));

// Using new Date and Base 36:
console.log((+new Date).toString(36).slice(-5));

// Using Math.random and Base 64 (btoa):
console.log(btoa(Math.random()).slice(0, 5));

// Using new Date and Base 64 (btoa):
console.log(btoa(+new Date).slice(-7, -2));
console.log(btoa(+new Date).substr(-7, 5));

Solution 7 - Javascript

Something like this should work

function randomString(len, charSet) {
	charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	var randomString = '';
	for (var i = 0; i < len; i++) {
		var randomPoz = Math.floor(Math.random() * charSet.length);
		randomString += charSet.substring(randomPoz,randomPoz+1);
	}
	return randomString;
}

Call with default charset [a-zA-Z0-9] or send in your own:

var randomValue = randomString(5);

var randomValue = randomString(5, 'PICKCHARSFROMTHISSET');

Solution 8 - Javascript

A newer version with es6 spread operator:

[...Array(30)].map(() => Math.random().toString(36)[2]).join('')

  • The 30 is an arbitrary number, you can pick any token length you want

  • The 36 is the maximum radix number you can pass to numeric.toString(), which means all numbers and a-z lowercase letters

  • The 2 is used to pick the 3rd index from the random string which looks like this: "0.mfbiohx64i", we could take any index after 0.

Solution 9 - Javascript

function randomstring(L) {
  var s = '';
  var randomchar = function() {
    var n = Math.floor(Math.random() * 62);
    if (n < 10) return n; //1-10
    if (n < 36) return String.fromCharCode(n + 55); //A-Z
    return String.fromCharCode(n + 61); //a-z
  }
  while (s.length < L) s += randomchar();
  return s;
}
console.log(randomstring(5));

Solution 10 - Javascript

Random String Generator (Alpha-Numeric | Alpha | Numeric)

/**
 * Pseudo-random string generator
 * http://stackoverflow.com/a/27872144/383904
 * Default: return a random alpha-numeric string
 * 
 * @param {Integer} len Desired length
 * @param {String} an Optional (alphanumeric), "a" (alpha), "n" (numeric)
 * @return {String}
 */
function randomString(len, an) {
  an = an && an.toLowerCase();
  var str = "",
    i = 0,
    min = an == "a" ? 10 : 0,
    max = an == "n" ? 10 : 62;
  for (; i++ < len;) {
    var r = Math.random() * (max - min) + min << 0;
    str += String.fromCharCode(r += r > 9 ? r < 36 ? 55 : 61 : 48);
  }
  return str;
}

console.log(randomString(10));      // i.e: "4Z8iNQag9v"
console.log(randomString(10, "a")); // i.e: "aUkZuHNcWw"
console.log(randomString(10, "n")); // i.e: "9055739230"


While the above uses additional checks for the desired A/N, A, N output, let's break it down the to the essentials (Alpha-Numeric only) for a better understanding:

  • Create a function that accepts an argument (desired length of the random String result)
  • Create an empty string like var str = ""; to concatenate random characters
  • Inside a loop create a rand index number from 0 to 61 (0..9+A..Z+a..z = 62)
  • Create a conditional logic to Adjust/fix rand (since it's 0..61) incrementing it by some number (see examples below) to get back the right CharCode number and the related Character.
  • Inside the loop concatenate to str a String.fromCharCode( incremented rand )

Let's picture the ASCII Character table ranges:

_____0....9______A..........Z______a..........z___________  Character
     | 10 |      |    26    |      |    26    |             Tot = 62 characters
    48....57    65..........90    97..........122           CharCode ranges

Math.floor( Math.random * 62 ) gives a range from 0..61 (what we need).
Let's fix the random to get the correct charCode ranges:

      |   rand   | charCode |  (0..61)rand += fix            = charCode ranges |
------+----------+----------+--------------------------------+-----------------+
0..9  |   0..9   |  48..57  |  rand += 48                    =     48..57      |
A..Z  |  10..35  |  65..90  |  rand += 55 /*  90-35 = 55 */  =     65..90      |
a..z  |  36..61  |  97..122 |  rand += 61 /* 122-61 = 61 */  =     97..122     |

The conditional operation logic from the table above:

   rand += rand>9 ? ( rand<36 ? 55 : 61 ) : 48 ;
// rand +=  true  ? (  true   ? 55 else 61 ) else 48 ;

From the explanation above, here's the resulting alpha-numeric snippet:

function randomString(len) {
  var str = "";                                // String result
  for (var i = 0; i < len; i++) {              // Loop `len` times
    var rand = Math.floor(Math.random() * 62); // random: 0..61
    var charCode = rand += rand > 9 ? (rand < 36 ? 55 : 61) : 48; // Get correct charCode
    str += String.fromCharCode(charCode);      // add Character to str
  }
  return str; // After all loops are done, return the concatenated string
}

console.log(randomString(10)); // i.e: "7GL9F0ne6t"

Or if you will:

const randomString = (n, r='') => {
  while (n--) r += String.fromCharCode((r=Math.random()*62|0, r+=r>9?(r<36?55:61):48));
  return r;
};

console.log(randomString(10))

Solution 11 - Javascript

To meet requirement [a-zA-Z0-9] and length=5 use

For Browser:

btoa(Math.random().toString()).substr(10, 5);

For NodeJS:

Buffer.from(Math.random().toString()).toString("base64").substr(10, 5);

Lowercase letters, uppercase letters, and numbers will occur.

(it's typescript compatible)

Solution 12 - Javascript

The simplest way is:

(new Date%9e6).toString(36)

This generate random strings of 5 characters based on the current time. Example output is 4mtxj or 4mv90 or 4mwp1

The problem with this is that if you call it two times on the same second, it will generate the same string.

The safer way is:

(0|Math.random()*9e6).toString(36)

This will generate a random string of 4 or 5 characters, always diferent. Example output is like 30jzm or 1r591 or 4su1a

In both ways the first part generate a random number. The .toString(36) part cast the number to a base36 (alphadecimal) representation of it.

Solution 13 - Javascript

Here are some easy one liners. Change new Array(5) to set the length.

###Including 0-9a-z

new Array(5).join().replace(/(.|$)/g, function(){return ((Math.random()*36)|0).toString(36);})

###Including 0-9a-zA-Z

new Array(5).join().replace(/(.|$)/g, function(){return ((Math.random()*36)|0).toString(36)[Math.random()<.5?"toString":"toUpperCase"]();});

Solution 14 - Javascript

I know everyone has got it right already, but i felt like having a go at this one in the most lightweight way possible(light on code, not CPU):

function rand(length, current) {
  current = current ? current : '';
  return length ? rand(--length, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz".charAt(Math.floor(Math.random() * 60)) + current) : current;
}

console.log(rand(5));

It takes a bit of time to wrap your head around, but I think it really shows how awesome javascript's syntax is.

Solution 15 - Javascript

Generate a secure random alphanumeric Base-62 string:

function generateUID(length)
{
    return window.btoa(Array.from(window.crypto.getRandomValues(new Uint8Array(length * 2))).map((b) => String.fromCharCode(b)).join("")).replace(/[+/]/g, "").substring(0, length);
}

console.log(generateUID(22)); // "yFg3Upv2cE9cKOXd7hHwWp"
console.log(generateUID(5)); // "YQGzP"

Solution 16 - Javascript

In case anyone is interested in a one-liner (although not formatted as such for your convenience) that allocates the memory at once (but note that for small strings it really does not matter) here is how to do it:

Array.apply(0, Array(5)).map(function() {
    return (function(charset){
        return charset.charAt(Math.floor(Math.random() * charset.length))
    }('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'));
}).join('')

You can replace 5 by the length of the string you want. Thanks to @AriyaHidayat in this post for the solution to the map function not working on the sparse array created by Array(5).

Solution 17 - Javascript

If you are using Lodash or Underscore, then it so simple:

var randomVal = _.sample('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 5).join('');

Solution 18 - Javascript

There is no best way to do this. You can do it any way you prefer, as long as the result suits your requirements. To illustrate, I've created many different examples, all which should provide the same end-result

Most other answers on this page ignore the upper-case character requirement.

Here is my fastest solution and most readable. It basically does the same as the accepted solution, except it is a bit faster.

function readableRandomStringMaker(length) {
  for (var s=''; s.length < length; s += 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.charAt(Math.random()*62|0));
  return s;
}
console.log(readableRandomStringMaker(length));
// e3cbN

Here is a compact, recursive version which is much less readable:

const compactRandomStringMaker = (length) => length-- && "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".charAt(Math.random()*62|0) + (compactRandomStringMaker(length)||"");
console.log(compactRandomStringMaker(5));
// DVudj

A more compact one-liner:

Array(5).fill().map(()=>"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".charAt(Math.random()*62)).join("")
// 12oEZ

A variation of the above:

"     ".replaceAll(" ",()=>"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".charAt(Math.random()*62))

The most compact one-liner, but inefficient and unreadable - it adds random characters and removes illegal characters until length is l:

((l,f=(p='')=>p.length<l?f(p+String.fromCharCode(Math.random()*123).replace(/[^a-z0-9]/i,'')):p)=>f())(5)

A cryptographically secure version, which is wasting entropy for compactness, and is a waste regardless because the generated string is so short:

[...crypto.getRandomValues(new Uint8Array(999))].map((c)=>String.fromCharCode(c).replace(/[^a-z0-9]/i,'')).join("").substr(0,5)
// 8fzPq

Or, without the length-argument it is even shorter:

((f=(p='')=>p.length<5?f(p+String.fromCharCode(Math.random()*123).replace(/[^a-z0-9]/i,'')):p)=>f())()
// EV6c9

Then a bit more challenging - using a nameless recursive arrow function:

((l,s=((l)=>l--&&"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".charAt(Math.random()*62|0)+(s(l)||""))) => s(l))(5);
// qzal4

This is a "magic" variable which provides a random character every time you access it:

const c = new class { [Symbol.toPrimitive]() { return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".charAt(Math.random()*62|0) } };
console.log(c+c+c+c+c);
// AgMnz

A simpler variant of the above:

const c=()=>"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".charAt(Math.random()*62|0);
c()+c()+c()+c()+c();
// 6Qadw

Solution 19 - Javascript

const c = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
const s = [...Array(5)].map(_ => c[~~(Math.random()*c.length)]).join('')

Solution 20 - Javascript

Here's the method I created.
It will create a string containing both uppercase and lowercase characters.
In addition I've included the function that will created an alphanumeric string too.

Working examples:
http://jsfiddle.net/greatbigmassive/vhsxs/ (alpha only)
http://jsfiddle.net/greatbigmassive/PJwg8/ (alphanumeric)

function randString(x){
    var s = "";
    while(s.length<x&&x>0){
        var r = Math.random();
        s+= String.fromCharCode(Math.floor(r*26) + (r>0.5?97:65));
    }
    return s;
}

Upgrade July 2015
This does the same thing but makes more sense and includes all letters.

var s = "";
while(s.length<x&&x>0){
    v = Math.random()<0.5?32:0;
    s += String.fromCharCode(Math.round(Math.random()*((122-v)-(97-v))+(97-v)));
}

Solution 21 - Javascript

Improved @Andrew's answer above :

Array.from({ length : 1 }, () => Math.random().toString(36)[2]).join('');

Base 36 conversion of the random number is inconsistent, so selecting a single indice fixes that. You can change the length for a string with the exact length desired.

Solution 22 - Javascript

Assuming you use underscorejs it's possible to elegantly generate random string in just two lines:

var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var random = _.sample(possible, 5).join('');

Solution 23 - Javascript

One liner:

Array(15).fill(null).map(() => Math.random().toString(36).substr(2)).join('')
// Outputs: 0h61cbpw96y83qtnunwme5lxk1i70a6o5r5lckfcyh1dl9fffydcfxddd69ada9tu9jvqdx864xj1ul3wtfztmh2oz2vs3mv6ej0fe58ho1cftkjcuyl2lfkmxlwua83ibotxqc4guyuvrvtf60naob26t6swzpil

Solution 24 - Javascript

Fast and improved algorithm. Does not guarantee uniform (see comments).

function getRandomId(length) {
    if (!length) {
        return '';
    }

    const possible =
        'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let array;

    if ('Uint8Array' in self && 'crypto' in self && length <= 65536) {
        array = new Uint8Array(length);
        self.crypto.getRandomValues(array);
    } else {
        array = new Array(length);

        for (let i = 0; i < length; i++) {
            array[i] = Math.floor(Math.random() * 62);
        }
    }

    let result = '';

    for (let i = 0; i < length; i++) {
        result += possible.charAt(array[i] % 62);
    }

    return result;
}

Solution 25 - Javascript

You can loop through an array of items and recursively add them to a string variable, for instance if you wanted a random DNA sequence:

function randomDNA(len) {
  len = len || 100
  var nuc = new Array("A", "T", "C", "G")
  var i = 0
  var n = 0
  s = ''
  while (i <= len - 1) {
    n = Math.floor(Math.random() * 4)
    s += nuc[n]
    i++
  }
  return s
}

console.log(randomDNA(5));

Solution 26 - Javascript

How about this compact little trick?

var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var stringLength = 5;

function pickRandom() {
    return possible[Math.floor(Math.random() * possible.length)];
}

var randomString = Array.apply(null, Array(stringLength)).map(pickRandom).join('');

You need the Array.apply there to trick the empty array into being an array of undefineds.

If you're coding for ES2015, then building the array is a little simpler:

var randomString = Array.from({ length: stringLength }, pickRandom).join('');

Solution 27 - Javascript

function randomString (strLength, charSet) {
	var result = [];
	
	strLength = strLength || 5;
	charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	
	while (strLength--) { // (note, fixed typo)
		result.push(charSet.charAt(Math.floor(Math.random() * charSet.length)));
	}
	
	return result.join('');
}

This is as clean as it will get. It is fast too, http://jsperf.com/ay-random-string.

Solution 28 - Javascript

The problem with responses to "I need random strings" questions (in whatever language) is practically every solution uses a flawed primary specification of string length. The questions themselves rarely reveal why the random strings are needed, but I would challenge you rarely need random strings of length, say 8. What you invariably need is some number of unique strings, for example, to use as identifiers for some purpose.

There are two leading ways to get strictly unique strings: deterministically (which is not random) and store/compare (which is onerous). What do we do? We give up the ghost. We go with probabilistic uniqueness instead. That is, we accept that there is some (however small) risk that our strings won't be unique. This is where understanding collision probability and entropy are helpful.

So I'll rephrase the invariable need as needing some number of strings with a small risk of repeat. As a concrete example, let's say you want to generate a potential of 5 million IDs. You don't want to store and compare each new string, and you want them to be random, so you accept some risk of repeat. As example, let's say a risk of less than 1 in a trillion chance of repeat. So what length of string do you need? Well, that question is underspecified as it depends on the characters used. But more importantly, it's misguided. What you need is a specification of the entropy of the strings, not their length. Entropy can be directly related to the probability of a repeat in some number of strings. String length can't.

And this is where a library like EntropyString can help. To generate random IDs that have less than 1 in a trillion chance of repeat in 5 million strings using entropy-string:

import {Random, Entropy} from 'entropy-string'

const random = new Random()
const bits = Entropy.bits(5e6, 1e12)

const string = random.string(bits)

> "44hTNghjNHGGRHqH9"

entropy-string uses a character set with 32 characters by default. There are other predefined characters sets, and you can specify your own characters as well. For example, generating IDs with the same entropy as above but using hex characters:

import {Random, Entropy, charSet16} from './entropy-string'

const random = new Random(charSet16)
const bits = Entropy.bits(5e6, 1e12)

const string = random.string(bits)

> "27b33372ade513715481f"

Note the difference in string length due to the difference in total number of characters in the character set used. The risk of repeat in the specified number of potential strings is the same. The string lengths are not. And best of all, the risk of repeat and the potential number of strings is explicit. No more guessing with string length.

Solution 29 - Javascript

Case Insensitive Alphanumeric Chars:

function randStr(len) {
  let s = '';
  while (s.length < len) s += Math.random().toString(36).substr(2, len - s.length);
  return s;
}

// usage
console.log(randStr(50));

The benefit of this function is that you can get different length random string and it ensures the length of the string.

Case Sensitive All Chars:

function randStr(len) { let s = ''; while (len--) s += String.fromCodePoint(Math.floor(Math.random() * (126 - 33) + 33)); return s; }

// usage
console.log(randStr(50));

Custom Chars

function randStr(len, chars='abc123') {
  let s = '';
  while (len--) s += chars[Math.floor(Math.random() * chars.length)];
  return s;
}

// usage
console.log(randStr(50));
console.log(randStr(50, 'abc'));
console.log(randStr(50, 'aab')); // more a than b

Solution 30 - Javascript

I did not find a clean solution for supporting both lowercase and uppercase characters.

Lowercase only support:

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

Building on that solution to support lowercase and uppercase:

Math.random().toString(36).substr(2, 5).split('').map(c => Math.random() < 0.5 ? c.toUpperCase() : c).join('');

Change the 5 in substr(2, 5) to adjust to the length you need.

Solution 31 - Javascript

Here is my approach (with TypeScript).

I've decided to write yet another response because I didn't see any simple solution using modern js and clean code.

const DEFAULT_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

function getRandomCharFromAlphabet(alphabet: string): string {
  return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
}

function generateId(idDesiredLength: number, alphabet = DEFAULT_ALPHABET): string {
  /**
   * Create n-long array and map it to random chars from given alphabet.
   * Then join individual chars as string
   */
  return Array.from({length: idDesiredLength}).map(() => {
    return getRandomCharFromAlphabet(alphabet);
  }).join('');
}

generateId(5); // jNVv7

Solution 32 - Javascript

Crypto-Strong

If you want to get crypto-strong string which meets your requirements (I see answer which use this but gives non valid answers) use

let pass = n=> [...crypto.getRandomValues(new Uint8Array(n))]
   .map((x,i)=>(i=x/255*61|0,String.fromCharCode(i+(i>9?i>35?61:55:48)))).join``

let pass = n=> [...crypto.getRandomValues(new Uint8Array(n))]
   .map((x,i)=>(i=x/255*61|0,String.fromCharCode(i+(i>9?i>35?61:55:48)))).join``

console.log(pass(5));

Update: thanks to Zibri comment I update code to get arbitrary-long password

Solution 33 - Javascript

One-liner using map that gives you full control on the length and characters.

const rnd = (len, chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') => [...Array(len)].map(() => chars.charAt(Math.floor(Math.random() * chars.length))).join('')

console.log(rnd(12))

Solution 34 - Javascript

Just a simple map or reduce implementation should suffice:

const charset: string =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

const random1: string = [...Array(5)]
  .map((_) => charset[Math.floor(Math.random() * charset.length)])
  .join("");

const random2: string = [...Array(5)]
  .reduce<string>(
    (acc) => acc += charset[Math.floor(Math.random() * charset.length)],
    "",
  );

Solution 35 - Javascript

This works for sure

<script language="javascript" type="text/javascript">
function randomString() {
 var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
 var string_length = 8;
 var randomstring = '';
 for (var i=0; i<string_length; i++) {
  var rnum = Math.floor(Math.random() * chars.length);
  randomstring += chars.substring(rnum,rnum+1);
 }
 document.randform.randomfield.value = randomstring;
}
</script>

Solution 36 - Javascript

Generate 10 characters long string. Length is set by parameter (default 10).

function random_string_generator(len) {
var len = len || 10;
var str = '';
var i = 0;

for(i=0; i<len; i++) {
    switch(Math.floor(Math.random()*3+1)) {
        case 1: // digit
            str += (Math.floor(Math.random()*9)).toString();
        break;

        case 2: // small letter
            str += String.fromCharCode(Math.floor(Math.random()*26) + 97); //'a'.charCodeAt(0));
        break;

        case 3: // big letter
            str += String.fromCharCode(Math.floor(Math.random()*26) + 65); //'A'.charCodeAt(0));
        break;

        default:
        break;
    }
}
return str;
}

Solution 37 - Javascript

How about something like this: Date.now().toString(36) Not very random, but short and quite unique every time you call it.

Solution 38 - Javascript

This is what I used. A combination of a couple here. I use it in a loop, and each ID it produces is unique. It might not be 5 characters, but it's guaranteed unique.

var newId =
    "randomid_" +
    (Math.random() / +new Date()).toString(36).replace(/[^a-z]+/g, '');

Solution 39 - Javascript

Here is a test script for the #1 answer (thank you @csharptest.net)

the script runs makeid() 1 million times and as you can see 5 isnt a very unique. running it with a char length of 10 is quite reliable. I've ran it about 50 times and haven't seen a duplicate yet :-)

note: node stack size limit exceeds around 4 million so you cant run this 5 million times it wont ever finish.

function makeid()
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 5; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

ids ={}
count = 0
for (var i = 0; i < 1000000; i++) {
	tempId = makeid();
	if (typeof ids[tempId] !== 'undefined') {
		ids[tempId]++;
		if (ids[tempId] === 2) {
			count ++;
		}
		count++;
	}else{
		ids[tempId] = 1;
	}
}
console.log("there are "+count+ ' duplicate ids');

Solution 40 - Javascript

You can use coderain. It's a library to generate random codes according to given pattern. Use # as a placeholder for upper and lowercase characters as well as digits:

var cr = new CodeRain("#####");
console.log(cr.next());

There are other placeholders like A for uppercase letters or 9 for digits.

What may be useful is that calling .next() will always give you a unique result so you don't have to worry about duplicates.

Here is a demo application that generates a list of unique random codes.

Full disclosure: I'm the author of coderain.

Solution 41 - Javascript

This one combines many of the answers give.

var randNo = Math.floor(Math.random() * 100) + 2 + "" + new Date().getTime() +  Math.floor(Math.random() * 100) + 2 + (Math.random().toString(36).replace(/[^a-zA-Z]+/g, '').substr(0, 5));

console.log(randNo);

I have been using it for 1 month with great results.

Solution 42 - Javascript

One liner [a-z]:

String.fromCharCode(97 + Math.floor(Math.random() * 26))

Solution 43 - Javascript

Expanding on Doubletap's elegant example by answering the issues Gertas and Dragon brought up. Simply add in a while loop to test for those rare null circumstances, and limit the characters to five.

function rndStr() {
    x=Math.random().toString(36).substring(7).substr(0,5);
    while (x.length!=5){
        x=Math.random().toString(36).substring(7).substr(0,5);
    }
    return x;
}

Here's a jsfiddle alerting you with a result: http://jsfiddle.net/pLJJ7/

Solution 44 - Javascript

If you want just A-Z:

randomAZ(n: number): string {
      return Array(n)
        .fill(null)
        .map(() => Math.random()*100%25 + 'A'.charCodeAt(0))
        .map(a => String.fromCharCode(a))
        .join('')
 }

Solution 45 - Javascript

If you are developing on node js, it is better to use crypto. Here is an example of implementing the randomStr() function

const crypto = require('crypto');
const charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz';
const randomStr = (length = 5) => new Array(length)
    .fill(null)
    .map(() => charset.charAt(crypto.randomInt(charset.length)))
    .join('');

If you are not working in a server environment, just replace the random number generator:

const charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz';
const randomStr = (length = 5) => new Array(length)
    .fill(null)
    .map(() => charset.charAt(Math.floor(Math.random() * charset.length)))
    .join('');

Solution 46 - Javascript

"12345".split('').map(function(){return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.charAt(Math.floor(62*Math.random()));}).join('');

//or

String.prototype.rand = function() {return this.split('').map(function(){return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.charAt(Math.floor(62*Math.random()));}).join('');};

will generate a random alpha-numeric string with the length of the first/calling string

Solution 47 - Javascript

Also based upon doubletap's answer, this one handles any length of random required characters (lower only), and keeps generating random numbers until enough characters have been collected.

function randomChars(len) {
    var chars = '';

    while (chars.length < len) {
        chars += Math.random().toString(36).substring(2);
    }

    // Remove unnecessary additional characters.
    return chars.substring(0, len);
}

Solution 48 - Javascript

If a library is a possibility, Chance.js might be of help: http://chancejs.com/#string

Solution 49 - Javascript

For a string with upper- and lowercase letters and digits (0-9a-zA-Z), this may be the version that minifies best:

function makeId(length) {
  var id = '';
  var rdm62;
  while (length--) {
   // Generate random integer between 0 and 61, 0|x works for Math.floor(x) in this case 
   rdm62 = 0 | Math.random() * 62; 
   // Map to ascii codes: 0-9 to 48-57 (0-9), 10-35 to 65-90 (A-Z), 36-61 to 97-122 (a-z)
   id += String.fromCharCode(rdm62 + (rdm62 < 10 ? 48 : rdm62 < 36 ? 55 : 61)) 
  }
  return id;
}

The content of this function minifies to 97 bytes, while the top answer needs 149 bytes (because of the characters list).

Solution 50 - Javascript

This is a slightly improved version of doubletap's answer. It considers gertas's comment about the case, when Math.random() returns 0, 0.5, 0.25, 0.125, etc.

((Math.random()+3*Number.MIN_VALUE)/Math.PI).toString(36).slice(-5)
  1. It prevents that zero gets passed to toString my adding the smallest float to Math.random().
  2. It ensures that the number passed to toString has enough digits by dividing through an almost irrational number.

Solution 51 - Javascript

How about this below... this will produce the really random values:

function getRandomStrings(length) {
  const value = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const randoms = [];
  for(let i=0; i < length; i++) {
     randoms.push(value[Math.floor(Math.random()*value.length)]);
  }
  return randoms.join('');
}

But if you looking for a shorter syntax one in ES6:

const getRandomStrings = length => Math.random().toString(36).substr(-length);

Solution 52 - Javascript

Generate any number of hexadecimal character (e.g. 32):

(function(max){let r='';for(let i=0;i<max/13;i++)r+=(Math.random()+1).toString(16).substring(2);return r.substring(0,max).toUpperCase()})(32);

Solution 53 - Javascript

Posting an ES6-compatible version for posterity. If this is called a lot, be sure to store the .length values into constant variables.

// USAGE:
//      RandomString(5);
//      RandomString(5, 'all');
//      RandomString(5, 'characters', '0123456789');
const RandomString = (length, style = 'frictionless', characters = '') => {
    const Styles = {
        'all':          allCharacters,
        'frictionless': frictionless,
        'characters':   provided
    }

    let result              = '';
    const allCharacters     = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    const frictionless      = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
    const provided          = characters;

    const generate = (set) => {
        return set.charAt(Math.floor(Math.random() * set.length));
    };

    for ( let i = 0; i < length; i++ ) {
        switch(Styles[style]) {
            case Styles.all:
                result += generate(allCharacters);
                break;
            case Styles.frictionless:
                result += generate(frictionless);
                break;
            case Styles.characters:
                result += generate(provided);
                break;
        }
    }
    return result;
}

export default RandomString;

Solution 54 - Javascript

",,,,,".replace(/,/g,function (){return "AzByC0xDwEv9FuGt8HsIrJ7qKpLo6MnNmO5lPkQj4RiShT3gUfVe2WdXcY1bZa".charAt(Math.floor(Math.random()*62))});

Solution 55 - Javascript

This stores 5 alphanumeric characters in variable c.

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

Solution 56 - Javascript

I loved the brievety of doubletap's Math.random().toString(36).substring(7) answer, but not that it had so many collisions as hacklikecrack correctly pointed out. It generated 11-chacter strings but has a duplicate rate of 11% in a sample size of 1 million.

Here's a longer (but still short) and slower alternative that had only 133 duplicates in a sample space of 1 million. In rare cases the string will still be shorter than 11 chars:

Math.abs(Math.random().toString().split('')
    .reduce(function(p,c){return (p<<5)-p+c})).toString(36).substr(0,11);

Solution 57 - Javascript

This is for firefox chrome code (addons and the like)

It can save you a few hours of research.

function randomBytes( amount )
{
	let bytes = Cc[ '@mozilla.org/security/random-generator;1' ]

		.getService         ( Ci.nsIRandomGenerator )
		.generateRandomBytes( amount, ''            )

	return bytes.reduce( bytes2Number )


	function bytes2Number( previousValue, currentValue, index, array )
	{
	  return Math.pow( 256, index ) * currentValue + previousValue
	}
}

Use it as:

let   strlen   = 5
    , radix    = 36
    , filename = randomBytes( strlen ).toString( radix ).splice( - strlen )

Solution 58 - Javascript

Put the characters as the thisArg in the map function will create a "one-liner":

Array.apply(null, Array(5))
.map(function(){ 
    return this[Math.floor(Math.random()*this.length)];
}, "abcdefghijklmnopqrstuvwxyz")
.join('');

Solution 59 - Javascript

A functional approach. This answer is only practical if the functional prerequisites can be leveraged in other parts of your app. The performance is probably junk, but it was super fun to write.

// functional prerequisites
const U = f=> f (f)
const Y = U (h=> f=> f (x=> h (h) (f) (x)))
const comp = f=> g=> x=> f (g (x))
const foldk = Y (h=> f=> y=> ([x, ...xs])=>
  x === undefined ? y : f (y) (x) (y=> h (f) (y) (xs)))
const fold = f=> foldk (y=> x=> k=> k (f (y) (x)))
const map = f=> fold (y=> x=> [...y, f (x)]) ([])
const char = x=> String.fromCharCode(x)
const concat = x=> y=> y.concat(x)
const concatMap = f=> comp (fold (concat) ([])) (map (f))
const irand = x=> Math.floor(Math.random() * x)
const sample = xs=> xs [irand (xs.length)]

// range : make a range from x to y; [x...y]
// Number -> Number -> [Number]
const range = Y (f=> r=> x=> y=>
  x > y ? r : f ([...r, x]) (x+1) (y)
) ([])

// srand : make random string from list or ascii code ranges
// [(Range a)] -> Number -> [a]
const srand = comp (Y (f=> z=> rs=> x=>
  x === 0 ? z : f (z + sample (rs)) (rs) (x-1)
) ([])) (concatMap (map (char)))

// idGenerator : make an identifier of specified length
// Number -> String
const idGenerator = srand ([
  range (48) (57),  // include 0-9
  range (65) (90),  // include A-Z
  range (97) (122)  // include a-z
])

console.log (idGenerator (6))  //=> TT688X
console.log (idGenerator (10)) //=> SzaaUBlpI1
console.log (idGenerator (20)) //=> eYAaWhsfvLDhIBID1xRh

In my opinion, it's hard to beat the clarity of idGenerator without adding magical, do-too-many-things functions.

A slight improvement could be

// ord : convert char to ascii code
// Char -> Number
const ord = x => x.charCodeAt(0)

// idGenerator : make an identifier of specified length
// Number -> String
const idGenerator = srand ([
  range (ord('0')) (ord('9')),
  range (ord('A')) (ord('Z')),
  range (ord('a')) (ord('z'))
])

Have fun with it. Let me know what you like/learn ^_^

Solution 60 - Javascript

Random numeric value (up to 16 digits)

/**
 * Random numeric value (up to 16 digits)
 * @returns {String}
 */
function randomUid () {
  return String(Math.floor(Math.random() * 9e15))
}

// randomUid() -> "3676724552601324"

Solution 61 - Javascript

Here is a different approach with fixed length by base, without RegExp replace lack (based on @bendytree's answer);

function rand(base) {
    // default base 10
    base = (base >= 2 && base <= 36) ? base : 10;
    for (var i = 0, ret = []; i < base; i++) {
        ret[i] = ((Math.random() * base) | 0).toString(base)
            // include 0-9a-zA-Z?
            // [Math.random() < .5 ? 'toString' : 'toUpperCase']();
    }
    return ret.join('');
}

Solution 62 - Javascript

Teach a man to fish:

Programmers cut paper with lasers, not chainsaws. Using fringe, language specific methods to produce the smallest, most obfuscated code is cute and all, but will never offer a complete solution. You have to use the right tool for the job.

What you want is a string of characters, and characters are represented by bytes. And, we can represent a byte in JavaScript using a number. So then, we should generate a list of these numbers, and cast them as strings. You don't need Date, or base64; Math.random() will get you a number, and String.fromCharCode() will turn it into a string. Easy.

But, which number equals which character? UTF-8 is the primary standard used on the web to interpret bytes as characters (although JavaScript uses UTF-16 internally, they overlap). The programmer's way of solving this problem is to look into the documentation.

UTF-8 lists all the keys on the keyboard in the numbers between 0 and 128. Some are non-printing. Simply pick out the characters you want in your random strings, and search for them, using randomly generated numbers.

Bellow is a function that takes a virtually infinite length, generates a random number in a loop, and searches for all the printing characters in the lower 128 UTF-8 codes. Entropy is inherent, since not all random numbers will hit every time (non-printing characters, white space, etc). It will also perform faster as you add more characters.

I've included most of the optimizations discussed in the thread:

  • The double tilde is faster than Math.floor
  • "if" statements are faster than regular expressions
  • pushing to an array is faster than string concatenation

function randomID(len) {
  var char;
  var arr = [];
  var len = len || 5;

  do {
    char = ~~(Math.random() * 128);

    if ((
        (char > 47 && char < 58) || // 0-9
        (char > 64 && char < 91) || // A-Z
        (char > 96 && char < 123) // a-z

        // || (char > 32 && char < 48) // !"#$%&,()*+'-./
        // || (char > 59 && char < 65) // <=>?@
        // || (char > 90 && char < 97) // [\]^_`
        // || (char > 123 && char < 127) // {|}~
      )
      //security conscious removals: " ' \ ` 
      //&& (char != 34 && char != 39 && char != 92 && char != 96) 

    ) { arr.push(String.fromCharCode(char)) }

  } while (arr.length < len);

  return arr.join('')
}

var input = document.getElementById('length');

input.onfocus = function() { input.value = ''; }

document.getElementById('button').onclick = function() {
  var view = document.getElementById('string');
  var is_number = str => ! Number.isNaN( parseInt(str));
    
  if ( is_number(input.value))
    view.innerText = randomID(input.value);
  else
    view.innerText = 'Enter a number';
}

#length {
  width: 3em;
  color: #484848;
}

#string {
  color: #E83838;
  font-family: 'sans-serif';
  word-wrap: break-word;
}

<input id="length" type="text" value='#'/>
<input id="button" type="button" value="Generate" />
<p id="string"></p>

Why do it in this tedious way? Because you can. You're a programmer. You can make a computer do anything! Besides, what if you want a string of Hebrew characters? It's not hard. Find those characters in the UTF-8 standard and search for them. Free yourself from these McDonald methods like toString(36).

Sometimes, dropping down to a lower level of abstraction is what's needed to create a real solution. Understanding the fundamental principals at hand can allow you to customize your code how you'd like. Maybe you want an infinitely generated string to fill a circular buffer? Maybe you want all of your generated strings to be palindromes? Why hold yourself back?

Solution 63 - Javascript

I have made a String prototype which can generate a random String with a given length.

You also can secify if you want special chars and you can avoid some.

/**
 * STRING PROTOTYPE RANDOM GENERATOR
 * Used to generate a random string
 * @param {Boolean} specialChars
 * @param {Number} length
 * @param {String} avoidChars
 */
String.prototype.randomGenerator = function (specialChars = false, length = 1, avoidChars = '') {
    let _pattern = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    _pattern += specialChars === true ? '(){}[]+-*/=' : '';
    if (avoidChars && avoidChars.length) {
        for (let char of avoidChars) {
            _pattern = _pattern.replace(char, '');
        }
    }
    let _random = '';
    for (let element of new Array(parseInt(length))) {
        _random += _pattern.charAt(Math.floor(Math.random() * _pattern.length));
    }
    return _random;
};

You can use like this :

// Generate password with specialChars which contains 10 chars and avoid iIlL chars
var password = String().randomGenerator(true, 10, 'iIlL');

Hope it helps.

Solution 64 - Javascript

Random unicode string

This method will return a random string with any of the supported unicode characters, which is not 100% what OP asks for, but what I was looking for:

function randomUnicodeString(length){
    return Array.from({length: length}, ()=>{
        return String.fromCharCode(Math.floor(Math.random() * (65536)))
    }).join('')
}
Rationale

This is the top result of google when searching for "random string javascript", but OP asks for a-zA-Z0-9 only.

Solution 65 - Javascript

As several people here have pointed out, passing the result of Math.random() directly to .string(36) has several problems.

It has poor randomness. The number of characters generated varies, and on average depends on the tricky details of how floating-point numbers work in Javascript. It seems to work if I am trying to generate 11 characters or fewer, but not with more than 11. And it is not flexible. There is no easy way to allow or prohibit certain characters.

I have a compact solution, which doesn't have these problems, for anyone using lodash:

_.range(11).map(i => _.sample("abcdefghijklmnopqrstuvwxyz0123456789")).join('')

If you want to allow certain characters (such as uppercase letters) or prohibit certain characters (like ambiguous characters such as l and 1), modify the string above.

Solution 66 - Javascript

I just write a simple package to generate a random token with given size, seed and mask. FYI.

@sibevin/random-token - https://www.npmjs.com/package/@sibevin/random-token

import { RandomToken } from '@sibevin/random-token'

RandomToken.gen({ length: 32 })
// JxpwdIA37LlHan4otl55PZYyyZrEdsQT

RandomToken.gen({ length: 32, seed: 'alphabet' })
// NbbtqjmHWJGdibjoesgomGHulEJKnwcI

RandomToken.gen({ length: 32, seed: 'number' })
// 33541506785847193366752025692500

RandomToken.gen({ length: 32, seed: 'oct' })
// 76032641643460774414624667410327

RandomToken.gen({ length: 32, seed: 'hex' })
// 07dc6320bf1c03811df7339dbf2c82c3

RandomToken.gen({ length: 32, seed: 'abc' })
// bcabcbbcaaabcccabaabcacbcbbabbac

RandomToken.gen({ length: 32, mask: '123abcABC' })
// vhZp88dKzRZGxfQHqfx7DOL8jKTkWUuO

Solution 67 - Javascript

How about extending the String object like so.

String.prototype.random = function(length) {
   var result = '';
   for (var i = 0; i < length; i++) {
      result += this.charAt(Math.floor(Math.random() * this.length));
   }

   return result;
};

using it:

console.log("ABCDEFG".random(5));

Solution 68 - Javascript

function generate(length) {
  var letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9"];
  var IDtext = "";
  var i = 0;
  while (i < length) {
    var letterIndex = Math.floor(Math.random() * letters.length);
    var letter = letters[letterIndex];
    IDtext = IDtext + letter;
    i++;
  }
  console.log(IDtext)
}

Solution 69 - Javascript

[..."abcdefghijklmnopqrsuvwxyz0123456789"].map((e, i, a) => a[Math.floor(Math.random() * a.length)]).join('')

Solution 70 - Javascript

Another nice way to randomize a string from the characters A-Za-z0-9:

function randomString(length) {
    if ( length <= 0 ) return "";
    var getChunk = function(){
        var i, //index iterator
            rand = Math.random()*10e16, //execute random once
            bin = rand.toString(2).substr(2,10), //random binary sequence
            lcase = (rand.toString(36)+"0000000000").substr(0,10), //lower case random string
            ucase = lcase.toUpperCase(), //upper case random string
            a = [lcase,ucase], //position them in an array in index 0 and 1
            str = ""; //the chunk string
        b = rand.toString(2).substr(2,10);
        for ( i=0; i<10; i++ )
            str += a[bin[i]][i]; //gets the next character, depends on the bit in the same position as the character - that way it will decide what case to put next
        return str;
    },
    str = ""; //the result string
    while ( str.length < length  )
        str += getChunk();
    str = str.substr(0,length);
    return str;
}

Solution 71 - Javascript

The npm module anyid provides flexible API to generate various kinds of string ID / code.

const id = anyid().encode('Aa0').length(5).random().id();

Solution 72 - Javascript

in below code i am generating random code for 8 characters

function RandomUnique(){
                    var charBank = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789";
                    var random= '';
                    var howmanycharacters = 8;
                    for (var i = 0; i < howmanycharacters ; i++) {
                        random+= charBank[parseInt(Math.random() * charBank.lenght)];
                    }
                    return random;
                }
        var random = RandomUnique();
        console.log(random);

Solution 73 - Javascript

Try this, what i use every time :

function myFunction() {
        var hash = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789";
        var random8 = '';
        for(var i = 0; i < 5; i++){
            random8 += hash[parseInt(Math.random()*hash.length)];
        }
        console.log(random8);
    document.getElementById("demo").innerHTML = "Your 5 character string ===> "+random8;
}        
        

<!DOCTYPE html>
<html>
<body>

<p>Click the button to genarate 5 character random string .</p>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>



</body>
</html>

Solution 74 - Javascript

very simple

function getRandomColor(){
  var color='';
  while(color.length<6){
    color=Math.floor(Math.random()*16777215).toString(16);
  }
  return '#'+color;
}

Solution 75 - Javascript

You could use base64:

function randomString(length)
{
    var rtn = "";
        
    do {
        rtn += btoa("" + Math.floor(Math.random() * 100000)).substring(0, length);
    }
    while(rtn.length < length);

    return rtn;
}

Solution 76 - Javascript

recursive solution:

function generateRamdomId (seedStr) {
const len = seedStr.length
console.log('possibleStr', seedStr , ' len ', len)
if(len <= 1){
    return seedStr
}
const randomValidIndex  = Math.floor(Math.random() * len)
const randomChar = seedStr[randomValidIndex]
const chunk1 = seedStr.slice(0, randomValidIndex)
const chunk2 = seedStr.slice(randomValidIndex +1)
const possibleStrWithoutRandomChar = chunk1.concat(chunk2)

return randomChar + generateRamdomId(possibleStrWithoutRandomChar)

}

you can use with the seed you want , dont repeat chars if you dont rea. Example

generateRandomId("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") 

Solution 77 - Javascript

Simple method:

function randomString(length) {
    let chars = [], output = '';
    for (let i = 32; i < 127; i ++) {
        chars.push(String.fromCharCode(i));
    }
    for (let i = 0; i < length; i ++) {
        output += chars[Math.floor(Math.random() * chars.length )];
    }
    return output;
}

If you want more or less characters change the "127" to something else.

Solution 78 - Javascript

Review

Many answers base on trick Math.random().toString(36) but the problem of this approach is that Math.random not always produce number which has at least 5 characters in base 36 e.g.

let testRnd = n => console.log(`num dec: ${n}, num base36: ${n.toString(36)}, string: ${n.toString(36).substr(2, 5)}`);


[
  Math.random(),
  // and much more less than 0.5...
  0.5,
  0.50077160493827161,
  0.5015432098765432,
  0.5023148148148148,
  0.5030864197530864,
  // and much more....
  0.9799597050754459
].map(n=>testRnd(n));

console.log('... and so on');

Each of below example (except first) numbers result with less than 5 characters (which not meet OP question requirements)

Here is "generator" which allows manually find such numbers

function base36Todec(hex) {
  hex = hex.split(/\./);
  return (parseInt(hex[1],36))*(36**-hex[1].length)+ +(parseInt(hex[0],36));
}

function calc(hex) {
  let dec = base36Todec(hex);
  msg.innerHTML = `dec: <b>${dec}</b><br>hex test: <b>${dec.toString(36)}</b>`
} 

function calc2(dec) {
  msg2.innerHTML = `dec: <b>${dec}</b><br>hex test: <b>${(+dec).toString(36)}</b>`
} 

let init="0.za1";
inp.value=init;
calc(init);

Type number in range 0-1 using base 36 (0-9,a-z) with less than 5 digits after dot<br>
<input oninput="calc(this.value)" id="inp" /><div id="msg"></div>
<br>
If above <i>hex test</i> give more digits than 5 after dot - then you can try to copy dec number to below field and join some digit to dec num right side and/or change last digit - it sometimes also produce hex with less digits<br>
<input oninput="calc2(this.value)" /><br><div id="msg2"></div>

I already give answer here so I will not put here another solution

Solution 79 - Javascript

The following code will produce a cryptographically secured random string of size containing [a-zA-Z0-9], using an npm package crypto-random-string. Install it using:

npm install crypto-random-string

To get a random string of 30 characters in the set [a-zA-Z0-9]:

const cryptoRandomString = require('crypto-random-string');
cryptoRandomString({length: 100, type: 'base64'}).replace(/[/+=]/g,'').substr(-30);

Summary: We are replacing /, +, = in a large random base64 string and getting the last N characters.

PS: Use -N in substr

Solution 80 - Javascript

In case you cannot type out a charset, using String.fromCharCode and a ranged Math.random allows you to create random strings in any Unicode codepoint range. For example, if you want 17 random Tibetan characters, you can input ranstr(17,0xf00,0xfff), where (0xf00,0xfff) corresponds to the Tibetan Unicode block. In my implementation, the generator will spit out ASCII text if you do not specify a codepoint range.

    function ranchar(a,b) {
       a = (a === undefined ? 0 : a);
       b = (b === undefined ? 127 : b);
       return String.fromCharCode(Math.floor(Math.random() * (b - a) + a)); 
    }
    
    function ranstr(len,a,b) {
      a = a || 32;
      var result = '';
      for(var i = 0; i < len; i++) {
       result += ranchar(a,b)
      }
      return result;
    }


//Here are some examples from random Unicode blocks
console.log('In Latin Basic block: '+ ranstr(10,0x0000,0x007f))
console.log('In Latin-1 Supplement block: '+ ranstr(10,0x0080,0x0ff))
console.log('In Currency Symbols block: ' + ranstr(10,0x20a0,0x20cf))
console.log('In Letterlike Symbols block: ' + ranstr(10,0x2100,0x214f))
console.log('In Dingbats block:' + ranstr(10,0x2700,0x27bf))

Solution 81 - Javascript

Love this SO question and their answers. So cleaver and creative solutions were proposed. I came up with mine that is wrapped inside a function that receives the length of the string you want to obtain plus a mode argument to decide how you want it to be composed.

Mode is a 3 length string that accepts only '1s' and '0s' that define what subsets of characters you want to include in the final string. It is grouped by 3 different subset( [0-9], [A-B], [a-b])

'100': [0-9]
'010': [A-B]
'101': [0-9] + [a-b]
'111': [0-9] + [A-B] + [a-b]

There are 8 possible combinations (2^N, witn N:#subsets). The '000' mode return an empty string.

function randomStr(l = 1, mode = '111') {
    if (mode === '000') return '';
    const r = (n) => Math.floor(Math.random() * n);
    const m = [...mode].map((v, i) => parseInt(v, 10) * (i + 1)).filter(Boolean).map((v) => v - 1);
    return [...new Array(l)].reduce((a) => a + String.fromCharCode([(48 + r(10)), (65 + r(26)), (97 + r(26))][m[r(m.length)]]), '')
}

A simple use case will be:

random = randomStr(50, '101')
// ii3deu9i4jk6dp4gx43g3059vss9uf7w239jl4itv0cth5tj3e
// Will give you a String[50] composed of [0-9] && [a-b] chars only.

The main idea here is to use the UNICODE table instead of randomizing hexadecimals as I saw in many answers. THe power of this approach is that you can extend it very easily to include others subsets of the UNICODE table with litte extra code in there that a random int(16) can't do.

Solution 82 - Javascript

Generate random strings with aA-zZ and 0-9 charachters collection. Just call this function with length parameter.

So to answer to this question: generateRandomString(5)

generateRandomString(length){
    let result = "", seeds

    for(let i = 0; i < length - 1; i++){
        //Generate seeds array, that will be the bag from where randomly select generated char
        seeds = [
            Math.floor(Math.random() * 10) + 48,
            Math.floor(Math.random() * 25) + 65,
            Math.floor(Math.random() * 25) + 97
        ]
        
        //Choise randomly from seeds, convert to char and append to result
        result += String.fromCharCode(seeds[Math.floor(Math.random() * 3)])
    }

    return result
}

Version that generates strings without numbers:

generateRandomString(length){
    let result = "", seeds

    for(let i = 0; i < length - 1; i++){
        seeds = [
            Math.floor(Math.random() * 25) + 65,
            Math.floor(Math.random() * 25) + 97
        ]
        result += String.fromCharCode(seeds[Math.floor(Math.random() * 2)])
    }

    return result
}

Solution 83 - Javascript

//To return a random letter

let alpha = "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
console.log(alpha.charAt(Math.floor(Math.random() * alpha.length)));

Solution 84 - Javascript

I use var randId = 'rand' + new Date().getTime();

Solution 85 - Javascript

Above All answers are perfect. but I am adding which is very good and rapid to generate any random string value

function randomStringGenerator(stringLength) {
  var randomString = ""; // Empty value of the selective variable
  const allCharacters = "'`~!@#$%^&*()_+-={}[]:;\'<>?,./|\\ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'"; // listing of all alpha-numeric letters
  while (stringLength--) {
    randomString += allCharacters.substr(Math.floor((Math.random() * allCharacters.length) + 1), 1); // selecting any value from allCharacters varible by using Math.random()
  }
  return randomString; // returns the generated alpha-numeric string
}

console.log(randomStringGenerator(10));//call function by entering the random string you want

or

console.log(Date.now())// it will produce random thirteen numeric character value every time.
console.log(Date.now().toString().length)// print length of the generated string

Solution 86 - Javascript

//creates a random code which is 10 in lenght,you can change it to yours at your will

function createRandomCode(length) {
    let randomCodes = '';
    let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let charactersLength = characters.length;
    for (let i = 0; i < length; i++ ) {
        randomCodes += characters.charAt(Math.floor(Math.random() * charactersLength))
    }
    console.log("your reference code is: ".toLocaleUpperCase() + randomCodes);
 };
 createRandomCode(10)

Solution 87 - Javascript

This is not a perfect solution, but it should work. If you ever get any error, then increase the value given in Uint8Array() constructor. The advantage of this method is it uses getRandomValues() method that generates cryptographically strong random values.

var array = new Uint8Array(20);
crypto.getRandomValues(array);
var arrayEncoded =  btoa(String.fromCharCode(...array)).split('');
var arrayFiltered = arrayEncoded.filter(value => {
	switch (value){
  	case "+" :
    	return false;
    case "/" :
    	return false;
    case "=" :
    	return false;
    default :
      return true;
   }
});
var password = arrayFiltered.slice(0,5).join('');
console.log(password);

A compact Version

var array = new Uint8Array(20);
crypto.getRandomValues(array);
var password = btoa(String.fromCharCode(...array)).split('').filter(value => {
		return !['+', '/' ,'='].includes(value);
}).slice(0,5).join('');
console.log(password);

Solution 88 - Javascript

To generate a hash from an array as a salt, [0,1,2,3] in this example, by this way we may be able to retrieve the hash later to populate a condition.

Simply feed a random array, or use as extra safe and fast finger-printing of arrays.

/* This method is very fast and is suitable into intensive loops */
/* Return a mix of uppercase and lowercase chars */

/* This will always output the same hash, since the salt array is the same */
console.log(
  btoa(String.fromCharCode(...new Uint8Array( [0,1,2,3] )))
)

/* Always output a random hex hash of here: 30 chars  */
console.log(
  btoa(String.fromCharCode(...new Uint8Array( Array(30).fill().map(() => Math.round(Math.random() * 30)) )))
)

Use HMAC from crypto API, for more: https://stackoverflow.com/a/56416039/2494754

Solution 89 - Javascript

Here is an example in CoffeeScript:

String::add_Random_Letters   = (size )->
                                         charSet = 'abcdefghijklmnopqrstuvwxyz'
                                         @ + (charSet[Math.floor(Math.random() * charSet.length)]  for i in [1..size]).join('')

which can be used

value = "abc_"
value_with_exta_5_random_letters = value.add_Random_Letters(5)

Solution 90 - Javascript

Here's Coffeescript version one line of code

genRandomString = (length,set) -> [0...length].map( -> set.charAt Math.floor(Math.random() * set.length)).join('')

Usage:

genRandomString 5, 'ABCDEFTGHIJKLMNOPQRSTUVWXYZ'

Output:

'FHOOV' # random string of length 5 in possible set A~Z

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
QuestionTom LehmanView Question on Stackoverflow
Solution 1 - Javascriptcsharptest.netView Answer on Stackoverflow
Solution 2 - JavascriptdoubletapView Answer on Stackoverflow
Solution 3 - JavascriptMulanView Answer on Stackoverflow
Solution 4 - JavascriptSilver RingveeView Answer on Stackoverflow
Solution 5 - JavascriptamichairView Answer on Stackoverflow
Solution 6 - JavascriptValentin PodkamennyiView Answer on Stackoverflow
Solution 7 - JavascriptCaffGeekView Answer on Stackoverflow
Solution 8 - JavascriptOr DuanView Answer on Stackoverflow
Solution 9 - JavascriptkennebecView Answer on Stackoverflow
Solution 10 - JavascriptRoko C. BuljanView Answer on Stackoverflow
Solution 11 - JavascriptSergio CabralView Answer on Stackoverflow
Solution 12 - JavascriptMasqueradeCircusView Answer on Stackoverflow
Solution 13 - JavascriptbendytreeView Answer on Stackoverflow
Solution 14 - JavascriptRoderick View Answer on Stackoverflow
Solution 15 - JavascriptgogoView Answer on Stackoverflow
Solution 16 - JavascriptMartijn de MillianoView Answer on Stackoverflow
Solution 17 - JavascriptvineetView Answer on Stackoverflow
Solution 18 - JavascriptfrodeborliView Answer on Stackoverflow
Solution 19 - JavascriptNahuel GrecoView Answer on Stackoverflow
Solution 20 - JavascriptAdamView Answer on Stackoverflow
Solution 21 - JavascriptZeeView Answer on Stackoverflow
Solution 22 - JavascripttiktakView Answer on Stackoverflow
Solution 23 - JavascriptiamarkadytView Answer on Stackoverflow
Solution 24 - JavascriptyaroslavView Answer on Stackoverflow
Solution 25 - JavascriptAndyView Answer on Stackoverflow
Solution 26 - JavascriptqubyteView Answer on Stackoverflow
Solution 27 - JavascriptGajusView Answer on Stackoverflow
Solution 28 - Javascriptdingo skyView Answer on Stackoverflow
Solution 29 - JavascriptAliView Answer on Stackoverflow
Solution 30 - JavascriptravishiView Answer on Stackoverflow
Solution 31 - JavascriptAdam PietrasiakView Answer on Stackoverflow
Solution 32 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 33 - JavascriptfrancisView Answer on Stackoverflow
Solution 34 - JavascriptFilip SemanView Answer on Stackoverflow
Solution 35 - JavascriptVigneshView Answer on Stackoverflow
Solution 36 - JavascriptropsiUView Answer on Stackoverflow
Solution 37 - JavascriptSwergasView Answer on Stackoverflow
Solution 38 - JavascriptAndrew PlankView Answer on Stackoverflow
Solution 39 - JavascriptJames HarringtonView Answer on Stackoverflow
Solution 40 - JavascriptLukasz WiktorView Answer on Stackoverflow
Solution 41 - JavascriptmiodusView Answer on Stackoverflow
Solution 42 - JavascriptThe Botly NoobView Answer on Stackoverflow
Solution 43 - JavascriptSteven DAmicoView Answer on Stackoverflow
Solution 44 - JavascriptDenys VitaliView Answer on Stackoverflow
Solution 45 - JavascriptСергей ДудкоView Answer on Stackoverflow
Solution 46 - JavascriptncluView Answer on Stackoverflow
Solution 47 - JavascriptqubyteView Answer on Stackoverflow
Solution 48 - JavascriptmindronesView Answer on Stackoverflow
Solution 49 - JavascriptWaruyamaView Answer on Stackoverflow
Solution 50 - JavascriptcevingView Answer on Stackoverflow
Solution 51 - JavascriptAlirezaView Answer on Stackoverflow
Solution 52 - JavascriptMarcView Answer on Stackoverflow
Solution 53 - JavascriptRickView Answer on Stackoverflow
Solution 54 - Javascriptguest271314View Answer on Stackoverflow
Solution 55 - JavascriptCollin AndersonView Answer on Stackoverflow
Solution 56 - JavascriptEricPView Answer on Stackoverflow
Solution 57 - Javascriptuser1115652View Answer on Stackoverflow
Solution 58 - Javascriptuser1506145View Answer on Stackoverflow
Solution 59 - JavascriptMulanView Answer on Stackoverflow
Solution 60 - JavascriptartnikproView Answer on Stackoverflow
Solution 61 - JavascriptK-GunView Answer on Stackoverflow
Solution 62 - JavascriptDucoView Answer on Stackoverflow
Solution 63 - JavascriptSparwView Answer on Stackoverflow
Solution 64 - JavascriptAutomaticoView Answer on Stackoverflow
Solution 65 - JavascriptElias ZamariaView Answer on Stackoverflow
Solution 66 - JavascriptSibevin WangView Answer on Stackoverflow
Solution 67 - Javascriptuser7793758View Answer on Stackoverflow
Solution 68 - JavascriptDominicentek GamingView Answer on Stackoverflow
Solution 69 - Javascriptdud3View Answer on Stackoverflow
Solution 70 - JavascriptSlavik MeltserView Answer on Stackoverflow
Solution 71 - JavascriptaleungView Answer on Stackoverflow
Solution 72 - JavascriptRatan Uday KumarView Answer on Stackoverflow
Solution 73 - Javascriptanil kumar DyavanapalliView Answer on Stackoverflow
Solution 74 - JavascriptBehnam MohammadiView Answer on Stackoverflow
Solution 75 - Javascriptuser1300214View Answer on Stackoverflow
Solution 76 - JavascriptPascual MuñozView Answer on Stackoverflow
Solution 77 - JavascriptNixinovaView Answer on Stackoverflow
Solution 78 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 79 - JavascriptjerrymouseView Answer on Stackoverflow
Solution 80 - JavascriptNirvanaView Answer on Stackoverflow
Solution 81 - Javascriptdenik1981View Answer on Stackoverflow
Solution 82 - JavascriptVictorView Answer on Stackoverflow
Solution 83 - JavascriptArunprasanth MView Answer on Stackoverflow
Solution 84 - JavascriptCMSView Answer on Stackoverflow
Solution 85 - JavascriptParth RavalView Answer on Stackoverflow
Solution 86 - JavascriptOlowu AbayomiView Answer on Stackoverflow
Solution 87 - JavascriptDon DilangaView Answer on Stackoverflow
Solution 88 - JavascriptNVRMView Answer on Stackoverflow
Solution 89 - JavascriptDinis CruzView Answer on Stackoverflow
Solution 90 - JavascriptAlstonView Answer on Stackoverflow