Skip to content

Instantly share code, notes, and snippets.

@6174
Created July 23, 2013 13:36
Show Gist options
  • Select an option

  • Save 6174/6062387 to your computer and use it in GitHub Desktop.

Select an option

Save 6174/6062387 to your computer and use it in GitHub Desktop.
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);
@rherugu

rherugu commented May 14, 2020

Copy link
Copy Markdown

nice

@abhidp

abhidp commented Jul 25, 2020

Copy link
Copy Markdown

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

this is a little better, you can specify any length 💪

where is the i being used? better off providing an empty function like this?

const randomString = (length) => [ ...Array(length) ].map(() => (~~(Math.random() * 36)).toString(36)).join('');

console.log(randomString(14));

@mmRoshani

Copy link
Copy Markdown

that's good, thanks😊

@jwpjrdev

jwpjrdev commented Sep 3, 2020

Copy link
Copy Markdown

So simple, so useful.

@pparadoxx

Copy link
Copy Markdown

thank you so much 👍

@VhMuzini

VhMuzini commented Oct 5, 2020

Copy link
Copy Markdown

Thank you

@MisaGu

MisaGu commented Oct 6, 2020

Copy link
Copy Markdown
Array.from({length:10}, () => String.fromCharCode(String(parseInt(65 + Math.random() * (122 - 65))).replace(/9[1-6]/,'90'))).join('')

@abhijit666

Copy link
Copy Markdown

Is there any simple way to generate string without numbers in it?

@jonathan-annett

Copy link
Copy Markdown

Is there any simple way to generate string without numbers in it?

const randcharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

const randchars = (function (R,M) {
    var L = R.length,r=M.random, f= M.floor;
    return function (len) {
        var i,s="";
        for (i=0;i<len;i++) s += R[f(r() * L)];
        return s;
    };
})(randcharset.split(''),Math);

for example

document.write("hello:"+randchars(4));

@adam-cyclones

Copy link
Copy Markdown

"doadiahdoiawd"

Of course you would have to type sporadically every time but I believe this is the fastest performing solution.

@s3rgeym

s3rgeym commented Jan 26, 2021

Copy link
Copy Markdown
// only printable
Array(8).fill().map(_ => String.fromCharCode(33 + Math.random() * (127 - 33))).join('')

@migue802

Copy link
Copy Markdown

Noice. 👌 Thanks!!

@usayamadx

Copy link
Copy Markdown

Awesome!!!

@BlueProgrammer212

Copy link
Copy Markdown

Pretty cool!

@GochaTamazi

Copy link
Copy Markdown

Brilliant!

@Montazu

Montazu commented Jan 6, 2022

Copy link
Copy Markdown

This is my version. Generate random string with numbers, lower and upper case.

const randomString=length=>Math.random().toString(36).substr(2,length).split("").map(e=>Math.random()<Math.random()?e.toUpperCase():e).join().replaceAll(",","");

console.log(randomString(10)); //8itPVoPBdU

@ughitsaaron

Copy link
Copy Markdown

Using recursion with the option of providing a prefix.

function randomStr(minLength = 0, acc = '') {
    if (acc.length <= minLength) {
        const str = Math.random().toString(36).slice(2);
        return randomStr(minLength, acc.concat(str))
    }

    return acc.slice(0, minLength);
}

randomStr(10) // => 'fvaj2hm2na'
randomStr(30, 'https://short.codes/') // => 'https://short.codes/jtmx66qr06'

@zeelkakdiya

Copy link
Copy Markdown
  const idString = async (string_length) => {
    var random_str = "";
    var characters =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZqeytrpolkadjsghfgmnbzxcvnQPOWEYRKASJHDGFMNBCVX--___-_jsfhrlg-_124903564576986483658fgh4sdfh687e4h897WETHJ68F7G4688471877GFHJFFGJ87469857468746hfghwrtiyj4598yhdjkhgnk";
    for (let index = 0; index < string_length; index++) {
      random_str += characters.charAt(
        Math.floor(Math.random() * characters.length)
      );
    }
    let string = `${random_str}`;
    console.log(string);
    return string;
  };

@adam-cyclones

adam-cyclones commented Jul 6, 2022

Copy link
Copy Markdown

@zeelkakdiya constructive feedback to improve this code:

  1. This is not an async function, it does not use promises
  2. var is used rather than let and in some cases const are more appropriate
  3. let string does not need ${}
  4. console.log is not useful in production code and actually slows down this function
  5. let string to return could be removed.
  6. casing is inconsistent
const generateID = (stringLength = 20) => {
    let randomStr = "";
    const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZqeytrpolkadjsghfgmnbzxcvnQPOWEYRKASJHDGFMNBCVX--___-_jsfhrlg-_124903564576986483658fgh4sdfh687e4h897WETHJ68F7G4688471877GFHJFFGJ87469857468746hfghwrtiyj4598yhdjkhgnk";
    for (let index = 0; index < stringLength; index++) {
      randomStr += characters.charAt(
        Math.floor(Math.random() * characters.length)
      );
    }
    return randomStr;
  };

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment