Generate random string/characters in JavaScript

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

    A newer version with es6 spread operator:

    [...Array(30)].map(() => Math.random().toString(36)[2]).join('')

    • The 30 is arbitrary number, you can pick any token length you want
    • The 36 is the maximum radix number you can pass to numeric.toString(), which means all numbers and a-z lowercase letters
    • The 2 is used to pick the 3th index from the random string which looks like this: "0.mfbiohx64i", we could take any index after 0.

提交回复
热议问题