Generate random string/characters in JavaScript

前端 未结 30 1764
闹比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:30

    Generate a secure random alphanumeric Base-62 string:

    function generateUID(length)
    {
        return window.btoa(Array.from(window.crypto.getRandomValues(new Uint8Array(length * 2))).map((b) => String.fromCharCode(b)).join("")).replace(/[+/]/g, "").substring(0, length);
    }
    
    console.log(generateUID(22)); // "yFg3Upv2cE9cKOXd7hHwWp"
    console.log(generateUID(5)); // "YQGzP"

    0 讨论(0)
  • 2020-11-21 07:31
    const c = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    const s = [...Array(5)].map(_ => c[~~(Math.random()*c.length)]).join('')
    
    0 讨论(0)
  • 2020-11-21 07:32

    The simplest way is:

    (new Date%9e6).toString(36)
    

    This generate random strings of 5 characters based on the current time. Example output is 4mtxj or 4mv90 or 4mwp1

    The problem with this is that if you call it two times on the same second, it will generate the same string.

    The safer way is:

    (0|Math.random()*9e6).toString(36)
    

    This will generate a random string of 4 or 5 characters, always diferent. Example output is like 30jzm or 1r591 or 4su1a

    In both ways the first part generate a random number. The .toString(36) part cast the number to a base36 (alphadecimal) representation of it.

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

    One liner:

    Array(15).fill(null).map(() => Math.random().toString(36).substr(2)).join('')
    // Outputs: 0h61cbpw96y83qtnunwme5lxk1i70a6o5r5lckfcyh1dl9fffydcfxffffd69ada9tu9jvqdx864xj1ul3wtfztmh2oz2vs3mv6ej0fe58ho1cftkjcuyl2lfkmxlwua83ibotxqc4guyuvrvtf60naob26t6swzpil
    
    0 讨论(0)
  • 2020-11-21 07:33

    You can loop through an array of items and recursively add them to a string variable, for instance if you wanted a random DNA sequence:

    function randomDNA(len) {
      len = len || 100
      var nuc = new Array("A", "T", "C", "G")
      var i = 0
      var n = 0
      s = ''
      while (i <= len - 1) {
        n = Math.floor(Math.random() * 4)
        s += nuc[n]
        i++
      }
      return s
    }
    
    console.log(randomDNA(5));

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

    If you are using Lodash or Underscore, then it so simple:

    var randomVal = _.sample('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 5).join('');
    
    0 讨论(0)
提交回复
热议问题