Create a random token in Javascript based on user details

后端 未结 6 921
醉酒成梦
醉酒成梦 2021-02-01 15:38

I want to create a random string (token) which can be used to identify a user whilst avoiding any potential conflicts with any other users\' tokens.

What I was thinking

6条回答
  •  忘了有多久
    2021-02-01 16:14

    It is very unlikely, but Math.random() could return 0.0. In that case, the solution of pimvdb would return "" (empty string). So, here is another solution, which returns in every case a random base36 with 10 chars length:

    function generateToken() {
        Math.floor(1000000000000000 + Math.random() * 9000000000000000)
              .toString(36).substr(0, 10)
    }
    

提交回复
热议问题