Generate random string/characters in JavaScript

前端 未结 30 1793
闹比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

    Improved @Andrew's answer above :

    Array.from({ length : 1 }, () => Math.random().toString(36)[2]).join('');
    

    Base 36 conversion of the random number is inconsistent, so selecting a single indice fixes that. You can change the length for a string with the exact length desired.

提交回复
热议问题