在 JS 中生成 random string 最常用的方式就是使用 Math.random() 方法。此方法可以返回 [0, 1) 之间的一个任意数字,生成之后我们可以将它转换成字符串,然后移除多余的字符。

  1. const randStr = Math.random().toString().substr(2, 8); // 32582362

这样就会生成一个包含8个数字字符的任意字符串。

我们也可以在 toString() 方法中传入一个 [2, 36] 之间整数值来定义进制。如果想生成一个二进制的数,可以传入 2,这样就会生成一个只包含0和1的任意字符串。

  1. const binary = Math.random().toString(2).substr(2, 8); // 01100101

若想生成一个完全任意的字符串,那你需要传入一个16或16以上的值:

  1. const randStr = Math.random().toString(16).substr(2, 8); // 03d48f70

据此,我们可以封装一个可以生成特定长度的任意字符串(1-13位):

  1. const randStr = (len = 3) => {
  2. return Math.random().toString(16).substr(2, len)
  3. }
  4. console.log(randStr(13)) // 660b82880a503

进制设置为 36 时,生成的最大长度是11位的字符。Math.random().toString(36).substr(2, 11)

生成更大长度的任意字符串

若想生成更大长度的任意字符串(13+),这时候就需要书写自己的生成器。这时候可以自己设置待组合的字符集,然后用函数去字符集里面取数并进行组合。使用 Math.random() 来取得任意的字符集的索引值,然后在进行拼接组合。

  1. const randStr = (length = 8) => {
  2. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  3. let str = ''
  4. const charsLength = chars.length
  5. for (let i = 0; i < length; i++) {
  6. str += chars.charAt(Math.floor(Math.random() * charsLength))
  7. }
  8. return str
  9. }
  10. console.log(randStr()) // F49chsNb
  11. console.log(randStr(16)) // 22PCjsc3hWMMO970