[javascript] Generate random string/characters in JavaScript

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?

This question is related to javascript string random

The answer is


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

Try this, what i use every time :

_x000D_
_x000D_
function myFunction() {_x000D_
        var hash = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789";_x000D_
        var random8 = '';_x000D_
        for(var i = 0; i < 5; i++){_x000D_
            random8 += hash[parseInt(Math.random()*hash.length)];_x000D_
        }_x000D_
        console.log(random8);_x000D_
    document.getElementById("demo").innerHTML = "Your 5 character string ===> "+random8;_x000D_
}        _x000D_
        
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<p>Click the button to genarate 5 character random string .</p>_x000D_
_x000D_
<button onclick="myFunction()">Click me</button>_x000D_
_x000D_
<p id="demo"></p>_x000D_
_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


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

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

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

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

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>

_x000D_
_x000D_
let r = Math.random().toString(36).substring(7);_x000D_
console.log("random", r);
_x000D_
_x000D_
_x000D_

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)

Case Insensitive Alphanumeric Chars:

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

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:

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

Custom Chars

_x000D_
_x000D_
function randStr(len, chars='abc123') {_x000D_
  let s = '';_x000D_
  while (len--) s += chars[Math.floor(Math.random() * chars.length)];_x000D_
  return s;_x000D_
}_x000D_
_x000D_
// usage_x000D_
console.log(randStr(50));_x000D_
console.log(randStr(50, 'abc'));_x000D_
console.log(randStr(50, 'aab')); // more a than b
_x000D_
_x000D_
_x000D_


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.


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.

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

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

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

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

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:

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


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


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 = [...crypto.getRandomValues(new Uint8Array(5))]
   .map((x,i)=>(i=x/255*61|0,String.fromCharCode(i+(i>9?i>35?61:55:48)))).join``

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

console.log(pass);
_x000D_
_x000D_
_x000D_


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


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.


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

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

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

very simple

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

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

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)

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.


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

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

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.


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

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

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

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

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

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

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.


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


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

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


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

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.

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


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

Short, easy and reliable

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

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

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.


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.

_x000D_
_x000D_
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');
_x000D_
Each of below example (except first) numbers result with less than 5 characters (which not meet OP question requirements)
_x000D_
_x000D_
_x000D_

Here is "generator" which allows manually find such numbers

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

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


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

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

Lowercase letters, uppercase letters, and numbers will occur.


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

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


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.


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/


Generate a secure random alphanumeric Base-62 string:

_x000D_
_x000D_
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"
_x000D_
_x000D_
_x000D_


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

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

or

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


function randomString (strLength, charSet) {
    var result = [];

    strLength = strLength || 5;
    charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    while (--strLength) {
        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.


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


"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


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"

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.

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

A compact Version

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


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.

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

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

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 -

_x000D_
_x000D_
// 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"
_x000D_
_x000D_
_x000D_


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


This one combines many of the answers give.

_x000D_
_x000D_
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));_x000D_
_x000D_
console.log(randNo);
_x000D_
_x000D_
_x000D_

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


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.


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

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.

_x000D_
_x000D_
// functional prerequisites_x000D_
const U = f=> f (f)_x000D_
const Y = U (h=> f=> f (x=> h (h) (f) (x)))_x000D_
const comp = f=> g=> x=> f (g (x))_x000D_
const foldk = Y (h=> f=> y=> ([x, ...xs])=>_x000D_
  x === undefined ? y : f (y) (x) (y=> h (f) (y) (xs)))_x000D_
const fold = f=> foldk (y=> x=> k=> k (f (y) (x)))_x000D_
const map = f=> fold (y=> x=> [...y, f (x)]) ([])_x000D_
const char = x=> String.fromCharCode(x)_x000D_
const concat = x=> y=> y.concat(x)_x000D_
const concatMap = f=> comp (fold (concat) ([])) (map (f))_x000D_
const irand = x=> Math.floor(Math.random() * x)_x000D_
const sample = xs=> xs [irand (xs.length)]_x000D_
_x000D_
// range : make a range from x to y; [x...y]_x000D_
// Number -> Number -> [Number]_x000D_
const range = Y (f=> r=> x=> y=>_x000D_
  x > y ? r : f ([...r, x]) (x+1) (y)_x000D_
) ([])_x000D_
_x000D_
// srand : make random string from list or ascii code ranges_x000D_
// [(Range a)] -> Number -> [a]_x000D_
const srand = comp (Y (f=> z=> rs=> x=>_x000D_
  x === 0 ? z : f (z + sample (rs)) (rs) (x-1)_x000D_
) ([])) (concatMap (map (char)))_x000D_
_x000D_
// idGenerator : make an identifier of specified length_x000D_
// Number -> String_x000D_
const idGenerator = srand ([_x000D_
  range (48) (57),  // include 0-9_x000D_
  range (65) (90),  // include A-Z_x000D_
  range (97) (122)  // include a-z_x000D_
])_x000D_
_x000D_
console.log (idGenerator (6))  //=> TT688X_x000D_
console.log (idGenerator (10)) //=> SzaaUBlpI1_x000D_
console.log (idGenerator (20)) //=> eYAaWhsfvLDhIBID1xRh
_x000D_
_x000D_
_x000D_

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 ^_^


One liner:

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

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

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


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:

_x000D_
_x000D_
function randomString(len) {_x000D_
  var str = "";                                // String result_x000D_
  for (var i = 0; i < len; i++) {              // Loop `len` times_x000D_
    var rand = Math.floor(Math.random() * 62); // random: 0..61_x000D_
    var charCode = rand += rand > 9 ? (rand < 36 ? 55 : 61) : 48; // Get correct charCode_x000D_
    str += String.fromCharCode(charCode);      // add Character to str_x000D_
  }_x000D_
  return str; // After all loops are done, return the concatenated string_x000D_
}_x000D_
_x000D_
console.log(randomString(10)); // i.e: "7GL9F0ne6t"
_x000D_
_x000D_
_x000D_

Or if you will:

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


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.


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

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 )

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

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.


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

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

_x000D_
_x000D_
function randomID(len) {_x000D_
  var char;_x000D_
  var arr = [];_x000D_
  var len = len || 5;_x000D_
_x000D_
  do {_x000D_
    char = ~~(Math.random() * 128);_x000D_
_x000D_
    if ((_x000D_
        (char > 47 && char < 58) || // 0-9_x000D_
        (char > 64 && char < 91) || // A-Z_x000D_
        (char > 96 && char < 123) // a-z_x000D_
_x000D_
        // || (char > 32 && char < 48) // !"#$%&,()*+'-./_x000D_
        // || (char > 59 && char < 65) // <=>?@_x000D_
        // || (char > 90 && char < 97) // [\]^_`_x000D_
        // || (char > 123 && char < 127) // {|}~_x000D_
      )_x000D_
      //security conscious removals: " ' \ ` _x000D_
      //&& (char != 34 && char != 39 && char != 92 && char != 96) _x000D_
_x000D_
    ) { arr.push(String.fromCharCode(char)) }_x000D_
_x000D_
  } while (arr.length < len);_x000D_
_x000D_
  return arr.join('')_x000D_
}_x000D_
_x000D_
var input = document.getElementById('length');_x000D_
_x000D_
input.onfocus = function() { input.value = ''; }_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
  var view = document.getElementById('string');_x000D_
  var is_number = str => ! Number.isNaN( parseInt(str));_x000D_
    _x000D_
  if ( is_number(input.value))_x000D_
    view.innerText = randomID(input.value);_x000D_
  else_x000D_
    view.innerText = 'Enter a number';_x000D_
}
_x000D_
#length {_x000D_
  width: 3em;_x000D_
  color: #484848;_x000D_
}_x000D_
_x000D_
#string {_x000D_
  color: #E83838;_x000D_
  font-family: 'sans-serif';_x000D_
  word-wrap: break-word;_x000D_
}
_x000D_
<input id="length" type="text" value='#'/>_x000D_
<input id="button" type="button" value="Generate" />_x000D_
<p id="string"></p>
_x000D_
_x000D_
_x000D_

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?


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

_x000D_
_x000D_
// Using Math.random and Base 36:_x000D_
console.log(Math.random().toString(36).slice(-5));_x000D_
_x000D_
// Using new Date and Base 36:_x000D_
console.log((+new Date).toString(36).slice(-5));_x000D_
_x000D_
// Using Math.random and Base 64 (btoa):_x000D_
console.log(btoa(Math.random()).slice(0, 5));_x000D_
_x000D_
// Using new Date and Base 64 (btoa):_x000D_
console.log(btoa(+new Date).slice(-7, -2));_x000D_
console.log(btoa(+new Date).substr(-7, 5));
_x000D_
_x000D_
_x000D_


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

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

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


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


This stores 5 alphanumeric characters in variable c.

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

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to random

How can I get a random number in Kotlin? scikit-learn random state in splitting dataset Random number between 0 and 1 in python In python, what is the difference between random.uniform() and random.random()? Generate random colors (RGB) Random state (Pseudo-random number) in Scikit learn How does one generate a random number in Apple's Swift language? How to generate a random string of a fixed length in Go? Generate 'n' unique random numbers within a range What does random.sample() method in python do?