Generate random string/characters in JavaScript

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

    I did not find a clean solution for supporting both lowercase and uppercase characters.

    Lowercase only support:

    Math.random().toString(36).substr(2, 5)

    Building on that solution to support lowercase and uppercase:

    Math.random().toString(36).substr(2, 5).split('').map(c => Math.random() < 0.5 ? c.toUpperCase() : c).join('');

    Change the 5 in substr(2, 5) to adjust to the length you need.

提交回复
热议问题