Generate random string/characters in JavaScript

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

提交回复
热议问题