Generate random string/characters in JavaScript

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

    function randomstring(L) {
      var s = '';
      var randomchar = function() {
        var n = Math.floor(Math.random() * 62);
        if (n < 10) return n; //1-10
        if (n < 36) return String.fromCharCode(n + 55); //A-Z
        return String.fromCharCode(n + 61); //a-z
      }
      while (s.length < L) s += randomchar();
      return s;
    }
    console.log(randomstring(5));

提交回复
热议问题