Generate random string/characters in JavaScript

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

    Here's the method I created.
    It will create a string containing both uppercase and lowercase characters.
    In addition I've included the function that will created an alphanumeric string too.

    Working examples:
    http://jsfiddle.net/greatbigmassive/vhsxs/ (alpha only)
    http://jsfiddle.net/greatbigmassive/PJwg8/ (alphanumeric)

    function randString(x){
        var s = "";
        while(s.length<x&&x>0){
            var r = Math.random();
            s+= String.fromCharCode(Math.floor(r*26) + (r>0.5?97:65));
        }
        return s;
    }
    

    Upgrade July 2015
    This does the same thing but makes more sense and includes all letters.

    var s = "";
    while(s.length<x&&x>0){
        v = Math.random()<0.5?32:0;
        s += String.fromCharCode(Math.round(Math.random()*((122-v)-(97-v))+(97-v)));
    }
    
    0 讨论(0)
  • 2020-11-21 07:10

    Improved @Andrew's answer above :

    Array.from({ length : 1 }, () => Math.random().toString(36)[2]).join('');
    

    Base 36 conversion of the random number is inconsistent, so selecting a single indice fixes that. You can change the length for a string with the exact length desired.

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

    Something like this should work

    function randomString(len, charSet) {
        charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        var randomString = '';
        for (var i = 0; i < len; i++) {
            var randomPoz = Math.floor(Math.random() * charSet.length);
            randomString += charSet.substring(randomPoz,randomPoz+1);
        }
        return randomString;
    }
    

    Call with default charset [a-zA-Z0-9] or send in your own:

    var randomValue = randomString(5);
    
    var randomValue = randomString(5, 'PICKCHARSFROMTHISSET');
    
    0 讨论(0)
  • 2020-11-21 07:11

    Here are some easy one liners. Change new Array(5) to set the length.

    Including 0-9a-z

    new Array(5).join().replace(/(.|$)/g, function(){return ((Math.random()*36)|0).toString(36);})
    

    Including 0-9a-zA-Z

    new Array(5).join().replace(/(.|$)/g, function(){return ((Math.random()*36)|0).toString(36)[Math.random()<.5?"toString":"toUpperCase"]();});
    
    0 讨论(0)
  • 2020-11-21 07:13

    Math.random is bad for this kind of thing

    Option 1

    If you're able to do this server-side, just use the crypto module -

    var crypto = require("crypto");
    var id = crypto.randomBytes(20).toString('hex');
    
    // "bb5dc8842ca31d4603d6aa11448d1654"
    

    The resulting string will be twice as long as the random bytes you generate; each byte encoded to hex is 2 characters. 20 bytes will be 40 characters of hex.


    Option 2

    If you have to do this client-side, perhaps try the uuid module -

    var uuid = require("uuid");
    var id = uuid.v4();
    
    // "110ec58a-a0f2-4ac4-8393-c866d813b8d1"
    

    Option 3

    If you have to do this client-side and you don't have to support old browsers, you can do it without dependencies -

    // dec2hex :: Integer -> String
    // i.e. 0-255 -> '00'-'ff'
    function dec2hex (dec) {
      return dec < 10
        ? '0' + String(dec)
        : dec.toString(16)
    }
    
    // generateId :: Integer -> String
    function generateId (len) {
      var arr = new Uint8Array((len || 40) / 2)
      window.crypto.getRandomValues(arr)
      return Array.from(arr, dec2hex).join('')
    }
    
    console.log(generateId())
    // "82defcf324571e70b0521d79cce2bf3fffccd69"
    
    console.log(generateId(20))
    // "c1a050a4cd1556948d41"


    For more information on crypto.getRandomValues -

    The crypto.getRandomValues() method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning).

    Here's a little console example -

    > var arr = new Uint8Array(4) # make array of 4 bytes (values 0-255)
    > arr
    Uint8Array(4) [ 0, 0, 0, 0 ]
    
    > window.crypto
    Crypto { subtle: SubtleCrypto }
    
    > window.crypto.getRandomValues()
    TypeError: Crypto.getRandomValues requires at least 1 argument, but only 0 were passed
    
    > window.crypto.getRandomValues(arr)
    Uint8Array(4) [ 235, 229, 94, 228 ]
    

    For IE11 support you can use -

    (window.crypto || window.msCrypto).getRandomValues(arr)
    

    For browser coverage see https://caniuse.com/#feat=getrandomvalues

    0 讨论(0)
  • 2020-11-21 07:13
    function randomString (strLength, charSet) {
        var result = [];
    
        strLength = strLength || 5;
        charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    
        while (--strLength) {
            result.push(charSet.charAt(Math.floor(Math.random() * charSet.length)));
        }
    
        return result.join('');
    }
    

    This is as clean as it will get. It is fast too, http://jsperf.com/ay-random-string.

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