Generate random string/characters in JavaScript

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

提交回复
热议问题