Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generate a random string in JavaScript In a short and fast way!
//http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
@kaxi1993

This comment has been minimized.

Copy link

kaxi1993 commented Jan 24, 2018

(Y)

@olegberman

This comment has been minimized.

Copy link

olegberman commented Mar 4, 2018

Awesome! Thank you!

@vuhanguyen

This comment has been minimized.

Copy link

vuhanguyen commented Apr 2, 2018

Thank you!

@dobri-dobrev

This comment has been minimized.

Copy link

dobri-dobrev commented Apr 2, 2018

Awesome!

@enricodeleo

This comment has been minimized.

Copy link

enricodeleo commented Apr 23, 2018

Very clever :)

@hoangthau

This comment has been minimized.

Copy link

hoangthau commented May 8, 2018

Great!

@ademoutlaw

This comment has been minimized.

Copy link

ademoutlaw commented Jun 4, 2018

very clever

@darklord1990

This comment has been minimized.

Copy link

darklord1990 commented Jun 6, 2018

That's great. Thank you!

@franher

This comment has been minimized.

Copy link

franher commented Jun 6, 2018

πŸ† πŸ’ͺ Thank you!

@camden-kid

This comment has been minimized.

Copy link

camden-kid commented Jun 16, 2018

Nice.

@liddack

This comment has been minimized.

Copy link

liddack commented Jul 12, 2018

What a fine bit of code. Obrigado :)

@tbanik

This comment has been minimized.

Copy link

tbanik commented Jul 18, 2018

[...Array(10)].map(i=>(~~(Math.random()*36)).toString(36)).join('')

this is a little better, you can specify any length πŸ’ͺ

@Demwunz

This comment has been minimized.

Copy link

Demwunz commented Aug 16, 2018

@tbanik, that's nice

@Shashika1992

This comment has been minimized.

Copy link

Shashika1992 commented Aug 22, 2018

Simple and nice!

@remino

This comment has been minimized.

Copy link

remino commented Aug 24, 2018

It's nice to generate random strings, but keep in mind that not all characters in a GUID or a UUID are random: https://en.wikipedia.org/wiki/Universally_unique_identifier

@volkanozcan2

This comment has been minimized.

Copy link

volkanozcan2 commented Sep 12, 2018

Perfect

@masecla22

This comment has been minimized.

Copy link

masecla22 commented Sep 14, 2018

Lovely!

@imfunniee

This comment has been minimized.

Copy link

imfunniee commented Sep 16, 2018

damn

@luispablo

This comment has been minimized.

Copy link

luispablo commented Sep 30, 2018

excellent!

@c7x43t

This comment has been minimized.

Copy link

c7x43t commented Oct 3, 2018

This one is very fast, good job.

@vamshikrishna01

This comment has been minimized.

Copy link

vamshikrishna01 commented Oct 9, 2018

Hi, I want only to have uppercase letter and numbers. How to achieve it?

@MelMacaluso

This comment has been minimized.

Copy link

MelMacaluso commented Oct 11, 2018

Hi, I want only to have uppercase letter and numbers. How to achieve it?

(Math.random().toString(36).substring(2, 16) + Math.random().toString(36).substring(2, 16)).toUpperCase()

@r-i-c-h

This comment has been minimized.

Copy link

r-i-c-h commented Oct 19, 2018

More concise way to generate random Hex Color string value I just found on SO, though a bit more JS voodoo:

'#'+(Math.random()*0xFFFFFF<<0).toString(16);

@GottZ

This comment has been minimized.

Copy link

GottZ commented Oct 25, 2018

[...Array(10)].map(i=>(~~(Math.random()*36)).toString(36)).join('')

@tbanik lemme beat that..

[...Array(10)].map(_=>(Math.random()*36|0).toString(36)).join``

@MelMacaluso you could do this:

const chars = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"];
// and then just do:
[...Array(10)].map(i=>chars[Math.random()*chars.length|0]).join``;
@dev-aitch

This comment has been minimized.

Copy link

dev-aitch commented Oct 29, 2018

@GottZ

[...Array(10)].map(i=>(~~(Math.random()*36)).toString(36)).join('')

@tbanik lemme beat that..

[...Array(10)].map(_=>(Math.random()*36|0).toString(36)).join ``

@MelMacaluso you could do this:

const chars = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"];
// and then just do:
[...Array(10)].map(i=>chars[Math.random()*chars.length|0]).join``;

What does [...Array(10)] means ? 10 array elements in ... :-/ ??

@xeonarno

This comment has been minimized.

Copy link

xeonarno commented Nov 15, 2018

@GottZ

[...Array(10)].map(i=>(~~(Math.random()*36)).toString(36)).join('')

@tbanik lemme beat that..
[...Array(10)].map(_=>(Math.random()*36|0).toString(36)).join ``
@MelMacaluso you could do this:

const chars = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"];
// and then just do:
[...Array(10)].map(i=>chars[Math.random()*chars.length|0]).join``;

What does [...Array(10)] means ? 10 array elements in ... :-/ ??

Array(10) create an Array Object with a length of 10 (but not 10 elements inside !)
the "..." is the spread operator and here allow to create an Array with 10 undefined element.
So at the end you have a nice Array with 10 cases void inside.

@fantomnotabene

This comment has been minimized.

Copy link

fantomnotabene commented Nov 18, 2018

[...Array(10)].map(i=>(~~(Math.random()*36)).toString(36)).join('')

this is a little better, you can specify any length

Length for array, but not for string.

String.random = function (length) {
	let radom13chars = function () {
		return Math.random().toString(16).substring(2, 15)
	}
	let loops = Math.ceil(length / 13)
	return new Array(loops).fill(radom13chars).reduce((string, func) => {
		return string + func()
	}, '').substring(0, length)
}
console.log(String.random(50))

Should be something like "bf81b27e5eb224dc2dd613dc8d96732ab23f5e930004dd09b5" (50 characters)

@khyamay

This comment has been minimized.

Copy link

khyamay commented Nov 19, 2018

@fantomnotabene Awesome just what I was looking for. Thanks.

@ledlamp

This comment has been minimized.

Copy link

ledlamp commented Dec 8, 2018

I think you can omit the second argument of substr and just do Math.random().toString(36).substring(2)

very good; just needed something simple for tmp file names.

@tdriancourt

This comment has been minimized.

Copy link

tdriancourt commented Dec 17, 2018

I think you can omit the second argument of substr and just do Math.random().toString(36).substring(2)

very good; just needed something simple for tmp file names.

I had the exact same need and i use the simplyfied version too.

Thank you !

@michaelkuijpers

This comment has been minimized.

Copy link

michaelkuijpers commented Dec 27, 2018

This is great! How to get this to a HTML paragraph?

@sourajshah

This comment has been minimized.

Copy link

sourajshah commented Feb 12, 2019

Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);

HOW CAN i change it for just i can get random number not alphabet ?

@ada-h

This comment has been minimized.

Copy link

ada-h commented Feb 14, 2019

Thank you!!

@getanwar

This comment has been minimized.

Copy link

getanwar commented Mar 27, 2019

Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);

HOW CAN i change it for just i can get random number not alphabet ?

Math.random().toFixed(36).substring(2, 15) + Math.random().toFixed(36).substring(2, 15);

@getanwar

This comment has been minimized.

Copy link

getanwar commented Mar 27, 2019

Or: Math.random().toFixed(36).substring(2, 38)

Remember this will be a string representation of numbers. Not a number type.

@ggtools

This comment has been minimized.

Copy link

ggtools commented May 3, 2019

My concern with it is that it's build on Math.random and according to MDN this function is not safe for cryptographic usages which is needed to have an usable UUID.

@zergius-eggstream

This comment has been minimized.

Copy link

zergius-eggstream commented May 13, 2019

If you want to get random string with exact length you should do something like that:

function getRandomString(length) {
  var s = '';
  do { s += Math.random().toString(36).substr(2); } while (s.length < length);
  s = s.substr(0, length);
  
  return s;
}

var uid = getRandomString(32);

because Math.random().toString(36) returns string with non-determined length

@jonathan-annett

This comment has been minimized.

Copy link

jonathan-annett commented May 19, 2019

possibly slightly more code than imagined, however there's 2 versions here - base36 as other suggestions use, and base64
both use math.random()*Number.MAX_SAFE_INTEGER as a basis for generating the random number

    function randomBase36Id(length) {
        length=typeof length==='number'?(length<4?4:length>2048?2048:length):16;
        var r = '';
        while (r.length<length) {
           r+=Math.ceil(Math.random()*Number.MAX_SAFE_INTEGER).toString(36);
        }
        return r.substr(Math.floor((r.length/2)-length/2),length);
    }
    
    //modifed from https://stackoverflow.com/a/6573119/830899
    var Base64 = {
    
        _Rixits :
    //   0       8       16      24      32      40      48      56     63
    //   v       v       v       v       v       v       v       v      v
        "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz$_",
        // You have the freedom, here, to choose the glyphs you want for 
        // representing your base-64 numbers. The ASCII encoding guys usually
        // choose a set of glyphs beginning with ABCD..., but, looking at
        // your update #2, I deduce that you want glyphs beginning with 
        // 0123..., which is a fine choice and aligns the first ten numbers
        // in base 64 with the first ten numbers in decimal.
    
        // This cannot handle negative numbers and only works on the 
        //     integer part, discarding the fractional part.
        // Doing better means deciding on whether you're just representing
        // the subset of javascript numbers of twos-complement 32-bit integers 
        // or going with base-64 representations for the bit pattern of the
        // underlying IEEE floating-point number, or representing the mantissae
        // and exponents separately, or some other possibility. For now, bail
        fromNumber : function(number) {
            if (isNaN(Number(number)) || number === null ||
                number === Number.POSITIVE_INFINITY)
                throw "The input is not valid";
            if (number < 0)
                throw "Can't represent negative numbers now";
    
            var rixit; // like 'digit', only in some non-decimal radix 
            var residual = Math.floor(number);
            var result = '';
            while (true) {
                rixit = residual % 64
                // console.log("rixit : " + rixit);
                // console.log("result before : " + result);
                result = this._Rixits.charAt(rixit) + result;
                // console.log("result after : " + result);
                // console.log("residual before : " + residual);
                residual = Math.floor(residual / 64);
                // console.log("residual after : " + residual);
    
                if (residual === 0)
                    break;
                }
            return result;
        },
    
        toNumber : function(rixits) {
            var result = 0;
            // console.log("rixits : " + rixits);
            // console.log("rixits.split('') : " + rixits.split(''));
            rixits = rixits.split('');
            for (var e = 0; e < rixits.length; e++) {
                // console.log("_Rixits.indexOf(" + rixits[e] + ") : " + 
                    // this._Rixits.indexOf(rixits[e]));
                // console.log("result before : " + result);
                result = (result * 64) + this._Rixits.indexOf(rixits[e]);
                // console.log("result after : " + result);
            }
            return result;
        }
    }
    
    function randomBase64Id(length) {
        length=typeof length==='number'?(length<4?4:length>2048?2048:length):16;
        var r = '';
        while (r.length<length) {
           r+=Base64.fromNumber(Math.ceil(Math.random()*Number.MAX_SAFE_INTEGER));
        }
        return r.substr(Math.floor((r.length/2)-length/2),length);
    }
@sureshbjra

This comment has been minimized.

Copy link

sureshbjra commented Jun 20, 2019

Awosome...

@Siiphanopas02

This comment has been minimized.

Copy link

Siiphanopas02 commented Jun 25, 2019

hello i want to make an order that generates 500 different please

@juliovedovatto

This comment has been minimized.

Copy link

juliovedovatto commented Jul 2, 2019

Thank you! πŸ™πŸ»

@felippetaw

This comment has been minimized.

Copy link

felippetaw commented Jul 19, 2019

niceeee!!

@aacassandra

This comment has been minimized.

Copy link

aacassandra commented Jul 29, 2019

Thank you! πŸ™πŸ»πŸ™πŸ»πŸ™πŸ», you save my day

@MelodicCrypter

This comment has been minimized.

Copy link

MelodicCrypter commented Aug 8, 2019

@tbanik, @MelMacaluso, @GottZ,

guys, your solutions are all wonderful so I made a little improvement out of it all.

const allCapsAlpha = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZ"]; 
const allLowerAlpha = [..."abcdefghijklmnopqrstuvwxyz"]; 
const allUniqueChars = [..."~!@#$%^&*()_+-=[]\{}|;:'",./<>?"];
const allNumbers = [..."0123456789"];

const base = [...allCapsAlpha, ...allNumbers, ...allLowerAlpha, ...allUniqueChars];

const generator = (base, len) => {
   return [...Array(len)]
     .map(i => base[Math.random()*base.length|0])
     .join('');
};

console.log('OUTPUT: ', generator(base, 28));

// OUTPUT: )ne]iGl'XBX%(FPCU:4JRnV'#mS=
// OUTPUT: kRY.}PZ~]Q|LQ1;qJ1Gnh>,zC{T@
@armavion

This comment has been minimized.

Copy link

armavion commented Aug 9, 2019

Nice and simple! Thanks

@bestwebdeveloper

This comment has been minimized.

Copy link

bestwebdeveloper commented Aug 15, 2019

@MelodicCrypter Cool solution. You just need to escape a double quote \" in allUniqueChars (single escape symbols are not rendered by github).

@nonara

This comment has been minimized.

Copy link

nonara commented Sep 9, 2019

Here's a little different spin.

  • Sets are attached to function (rnd.num, rnd,alphaLower, etc.)
  • Sequential sets are generated using fromCharCode
  • Uses generator function
  • Uses rest params for sets - ie rnd([length], [set1], [set2], ...)

See examples for use

const rnd = (() => {
    const gen = (min, max) => max++ && [...Array(max-min)].map((s, i) => String.fromCharCode(min+i));

    const sets = {
        num: gen(48,57),
        alphaLower: gen(97,122),
        alphaUpper: gen(65,90),
        special: [...`~!@#$%^&*()_+-=[]\{}|;:'",./<>?`]
    };

    function* iter(len, set) {
        if (set.length < 1) set = Object.values(sets).flat(); 
        for (let i = 0; i < len; i++) yield set[Math.random() * set.length|0]
    }

    return Object.assign(((len, ...set) => [...iter(len, set.flat())].join('')), sets);
})();


console.log('OUTPUT: ', rnd(20));    // Use all sets
// OUTPUT:  Kr8K1,f5hQa;YJC~7K9z

console.log('OUTPUT: ', rnd(20, rnd.alphaLower));
// OUTPUT:  cpjbkwvslxsofzvkekcw

console.log('OUTPUT: ', rnd(20, rnd.alphaUpper rnd.special));
// OUTPUT:  S]|-X]=N}TZC,GE;=,.D
@karfau

This comment has been minimized.

Copy link

karfau commented Oct 27, 2019

keep in mind that Math.random can also return 0 and that some conversions using .toString(n) might be much shorter that the number of chars you expect according to the second argument of substr/substring: https://jsfiddle.net/karfau/5632zu84/27/

@GottZ

This comment has been minimized.

Copy link

GottZ commented Oct 28, 2019

hey there. just want you to let this sink in for a moment:
https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#Examples

just for the lulz i made this:

public domain:

const random = (function() {
  const buffer = new Uint8Array(32);
  let index;
  let bitIndex;
  const max = BigInt(buffer.length);

  const reset = function() {
    index = 0n;
    bitIndex = 0n;
    crypto.getRandomValues(buffer);
  };
  reset();

  const getBits = function(count) {
    let bits = 0n;
    while (count > 0n) {
      const todo = count < 8n - bitIndex ? count : 8n - bitIndex;
      count -= todo;
      bits = bits << todo;
      bits += (BigInt(buffer[index]) >> bitIndex) & ((1n << todo) -1n);
      bitIndex += todo;
      if (bitIndex === 8n) {
        bitIndex = 0n;
        index++;
      }
      if (index === max) {
        reset();
      }
    }
    return bits;
  };

  const countBits = function(num) {
    let bitCount = 0n;
    while (num > 0n) {
      bitCount++;
      num = num >> 1n;
    }
    return bitCount;
  };

  const getN = function(max, bitCount) {
    if (max <= 0n) {
      throw new Error("this does not compute unless you want an infinite loop");
    }
    let out;

    do {
      out = getBits(bitCount);
    } while (out >= max);

    return out;
  };

  return function(input, count) {
    let wasNumber = false;
    let wasString = false;

    switch (typeof input) {
      default: {
        throw new Error("unsupported input");
      }
      case "number": {
        wasNumber = true;
        input = BigInt(input);
      }
      case "bigint": {
        const out = getN(input, countBits(max));
        return wasNumber ? Number(out) : out;
      }
      case "string": {
        wasString = true;
        input = input.split("");
      }
      case "object": {
        if (!Array.isArray(input)) {
          throw new Error("objects are not supported here");
        }
        if (typeof count != "number" && typeof count != "bigint") {
          throw new Error("you need to specify a count");
        }
        const contentCount = BigInt(input.length);
        const bitCount = countBits(contentCount);
        const out = [...Array(count)].map(_=> {
          return input[getN(contentCount, bitCount)];
        });
        return wasString ? out.join("") : out;
      }
    }
  };
})();

random("such String", 20); would return a string with 20 characters randomly made out of the given input string.
like: "r gsuhuSrtrguintughc"
random("10", 20) would generate random bits as string: "10011001011000111010"

if you provide an array, it will also return an array:
random("The quick brown Fox jumps over the lazy Dog".split(" "), 5);
returns something like:
["over","The","Dog","Fox","over"]

now the mindblow.. when using an array, the type of the content is interchangable. you can use objects, numbers, what ever you like.

now.. how to random sort an array with this you may ask..

there you go:

const randomSort = function(array) {
  const tmp = [];

  while(array.length > 0) tmp.push(array.splice(random(array.length), 1)[0]);

  array.push(...tmp);
  return array;
};
};

const array = ["foo", "bar", "asdfg", "rofl", "lol"];
randomSort(array);
console.dir(array); // something like: ["asdfg","bar","lol","rofl","foo"]

i was a bit too lazy to write a class for this.
also const buffer = new Uint8Array(32); could be reduced to const buffer = new Uint8Array(1); but i GUESS calling crypto.getRandomValues will in itself cause a performance penalty while buffering a little bit for the future is probably slightly faster.
just a guess though. i did not benchmark this.

also sorry for not providing comments here. i just made this code out of the blue. simple braingasm.

while using Math.pow and Math.min i was getting "bigint cannot be converted to number" issues thus i just wrote them with ternary.

keep in mind, the buffer usage will differ each run.
it is throwing out bit sequences that were exceeding the amount of items inside the input data.

also sadly there is no log2 in javascripts native bigint yet so i cannot count bits efficiently.

oh and ofc it works with emoji too:
random(["πŸ•","πŸš”","πŸŽ‰","βœ”","🎁","πŸ’©"], 20).join("");
returns something like: πŸš”πŸ’©βœ”πŸŽπŸŽ‰πŸš”πŸ’©πŸŽπŸš”πŸŽπŸŽπŸ•πŸ’©πŸ•πŸŽ‰πŸš”πŸš”πŸŽ‰πŸš”πŸŽ

oh and @MelodicCrypter you might like this :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.