Generate random string/characters in JavaScript

前端 未结 30 1775
闹比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))

提交回复
热议问题