Generate random string/characters in JavaScript

前端 未结 30 1839
闹比i
闹比i 2020-11-21 06:34

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?

相关标签:
30条回答
  • 2020-11-21 07:14

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

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


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

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

    Let's picture the ASCII Character table ranges:

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

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

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

    The conditional operation logic from the table above:

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

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

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

    Or if you will:

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

    0 讨论(0)
  • 2020-11-21 07:14

    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('');
    
    0 讨论(0)
  • 2020-11-21 07:15

    I think this will work for you:

    function makeid(length) {
       var result           = '';
       var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
       var charactersLength = characters.length;
       for ( var i = 0; i < length; i++ ) {
          result += characters.charAt(Math.floor(Math.random() * charactersLength));
       }
       return result;
    }
    
    console.log(makeid(5));

    0 讨论(0)
  • 2020-11-21 07:15

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

    0 讨论(0)
  • 2020-11-21 07:16

    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('');
    
    0 讨论(0)
  • 2020-11-21 07:17

    A newer version with es6 spread operator:

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

    • The 30 is 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 3th index from the random string which looks like this: "0.mfbiohx64i", we could take any index after 0.
    0 讨论(0)
提交回复
热议问题