Generate random string/characters in JavaScript

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

    function randomstring(L) {
      var s = '';
      var randomchar = function() {
        var n = Math.floor(Math.random() * 62);
        if (n < 10) return n; //1-10
        if (n < 36) return String.fromCharCode(n + 55); //A-Z
        return String.fromCharCode(n + 61); //a-z
      }
      while (s.length < L) s += randomchar();
      return s;
    }
    console.log(randomstring(5));

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

    The problem with responses to "I need random strings" questions (in whatever language) is practically every solution uses a flawed primary specification of string length. The questions themselves rarely reveal why the random strings are needed, but I would challenge you rarely need random strings of length, say 8. What you invariably need is some number of unique strings, for example, to use as identifiers for some purpose.

    There are two leading ways to get strictly unique strings: deterministically (which is not random) and store/compare (which is onerous). What do we do? We give up the ghost. We go with probabilistic uniqueness instead. That is, we accept that there is some (however small) risk that our strings won't be unique. This is where understanding collision probability and entropy are helpful.

    So I'll rephrase the invariable need as needing some number of strings with a small risk of repeat. As a concrete example, let's say you want to generate a potential of 5 million IDs. You don't want to store and compare each new string, and you want them to be random, so you accept some risk of repeat. As example, let's say a risk of less than 1 in a trillion chance of repeat. So what length of string do you need? Well, that question is underspecified as it depends on the characters used. But more importantly, it's misguided. What you need is a specification of the entropy of the strings, not their length. Entropy can be directly related to the probability of a repeat in some number of strings. String length can't.

    And this is where a library like EntropyString can help. To generate random IDs that have less than 1 in a trillion chance of repeat in 5 million strings using entropy-string:

    import {Random, Entropy} from 'entropy-string'
    
    const random = new Random()
    const bits = Entropy.bits(5e6, 1e12)
    
    const string = random.string(bits)
    

    "44hTNghjNHGGRHqH9"

    entropy-string uses a character set with 32 characters by default. There are other predefined characters sets, and you can specify your own characters as well. For example, generating IDs with the same entropy as above but using hex characters:

    import {Random, Entropy, charSet16} from './entropy-string'
    
    const random = new Random(charSet16)
    const bits = Entropy.bits(5e6, 1e12)
    
    const string = random.string(bits)
    

    "27b33372ade513715481f"

    Note the difference in string length due to the difference in total number of characters in the character set used. The risk of repeat in the specified number of potential strings is the same. The string lengths are not. And best of all, the risk of repeat and the potential number of strings is explicit. No more guessing with string length.

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

    Short, easy and reliable

    Returns exactly 5 random characters, as opposed to some of the top rated answers found here.

    Math.random().toString(36).substr(2, 5);
    
    0 讨论(0)
  • 2020-11-21 07:28

    Fast and improved algorithm. Does not guarantee uniform (see comments).

    function getRandomId(length) {
        if (!length) {
            return '';
        }
    
        const possible =
            'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let array;
    
        if ('Uint8Array' in self && 'crypto' in self && length <= 65536) {
            array = new Uint8Array(length);
            self.crypto.getRandomValues(array);
        } else {
            array = new Array(length);
    
            for (let i = 0; i < length; i++) {
                array[i] = Math.floor(Math.random() * 62);
            }
        }
    
        let result = '';
    
        for (let i = 0; i < length; i++) {
            result += possible.charAt(array[i] % 62);
        }
    
        return result;
    }
    
    0 讨论(0)
  • 2020-11-21 07:29

    In case anyone is interested in a one-liner (although not formatted as such for your convenience) that allocates the memory at once (but note that for small strings it really does not matter) here is how to do it:

    Array.apply(0, Array(5)).map(function() {
        return (function(charset){
            return charset.charAt(Math.floor(Math.random() * charset.length))
        }('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'));
    }).join('')
    

    You can replace 5 by the length of the string you want. Thanks to @AriyaHidayat in this post for the solution to the map function not working on the sparse array created by Array(5).

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

    To meet requirement [a-zA-Z0-9] and length=5 use

    btoa(Math.random()).substr(10, 5);
    

    Lowercase letters, uppercase letters, and numbers will occur.

    0 讨论(0)
提交回复
热议问题