Generate random string/characters in JavaScript

前端 未结 30 1834
闹比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.length0){
            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.length0){
        v = Math.random()<0.5?32:0;
        s += String.fromCharCode(Math.round(Math.random()*((122-v)-(97-v))+(97-v)));
    }
    

提交回复
热议问题