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

commented Jan 24, 2018

(Y)

@olegberman

This comment has been minimized.

Copy link

commented Mar 4, 2018

Awesome! Thank you!

@vuhanguyen

This comment has been minimized.

Copy link

commented Apr 2, 2018

Thank you!

@dobri-dobrev

This comment has been minimized.

Copy link

commented Apr 2, 2018

Awesome!

@enricodeleo

This comment has been minimized.

Copy link

commented Apr 23, 2018

Very clever :)

@hoangthau

This comment has been minimized.

Copy link

commented May 8, 2018

Great!

@ademoutlaw

This comment has been minimized.

Copy link

commented Jun 4, 2018

very clever

@darklord1990

This comment has been minimized.

Copy link

commented Jun 6, 2018

That's great. Thank you!

@franher

This comment has been minimized.

Copy link

commented Jun 6, 2018

🏆 💪 Thank you!

@camden-kid

This comment has been minimized.

Copy link

commented Jun 16, 2018

Nice.

@liddack

This comment has been minimized.

Copy link

commented Jul 12, 2018

What a fine bit of code. Obrigado :)

@tbanik

This comment has been minimized.

Copy link

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

commented Aug 16, 2018

@tbanik, that's nice

@Shashika1992

This comment has been minimized.

Copy link

commented Aug 22, 2018

Simple and nice!

@remino

This comment has been minimized.

Copy link

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

commented Sep 12, 2018

Perfect

@masecla22

This comment has been minimized.

Copy link

commented Sep 14, 2018

Lovely!

@imfunniee

This comment has been minimized.

Copy link

commented Sep 16, 2018

damn

@luispablo

This comment has been minimized.

Copy link

commented Sep 30, 2018

excellent!

@c7x43t

This comment has been minimized.

Copy link

commented Oct 3, 2018

This one is very fast, good job.

@vamshikrishna01

This comment has been minimized.

Copy link

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

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

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

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

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

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

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

commented Nov 19, 2018

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

@ledlamp

This comment has been minimized.

Copy link

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

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

commented Dec 27, 2018

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

@sourajshah

This comment has been minimized.

Copy link

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

commented Feb 14, 2019

Thank you!!

@getanwar

This comment has been minimized.

Copy link

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

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

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

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

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

commented Jun 20, 2019

Awosome...

@Siiphanopas02

This comment has been minimized.

Copy link

commented Jun 25, 2019

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

@juliovedovatto

This comment has been minimized.

Copy link

commented Jul 2, 2019

Thank you! 🙏🏻

@felippetaw

This comment has been minimized.

Copy link

commented Jul 19, 2019

niceeee!!

@aacassandra

This comment has been minimized.

Copy link

commented Jul 29, 2019

Thank you! 🙏🏻🙏🏻🙏🏻, you save my day

@MelodicCrypter

This comment has been minimized.

Copy link

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

commented Aug 9, 2019

Nice and simple! Thanks

@bestwebdeveloper

This comment has been minimized.

Copy link

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

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