Generate random string/characters in JavaScript

前端 未结 30 1777
闹比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: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');
    

提交回复
热议问题