最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cross browser random string (Math.random()*1e32).toString(36) - Stack Overflow

programmeradmin2浏览0评论

I use (Math.random()*1e32).toString(36) as a simple random string generator. It is very simple and works well and fullfils my needs (a temporal random to be used for ids, etc)

In chrome, safari, firefox and ie Math.random()*1e32 generates numbers like: 8.357963780872523e+31 :-)

  • In chrome, safari and firefox such number is converted into a string (8.357963780872523e+31).toString(36) -> 221fr2y11ebk4cog84wok which is exactly I want.
  • However in ie11 the string result is 6.936gwtrpf69(e+20).

How can I get the same string 221fr2y11ebk4cog84wokfrom 8.357963780872523e+31 in a cross browser manner?

BTW: I got the idea of this random string from this thread: Random alpha-numeric string in JavaScript?

I use (Math.random()*1e32).toString(36) as a simple random string generator. It is very simple and works well and fullfils my needs (a temporal random to be used for ids, etc)

In chrome, safari, firefox and ie Math.random()*1e32 generates numbers like: 8.357963780872523e+31 :-)

  • In chrome, safari and firefox such number is converted into a string (8.357963780872523e+31).toString(36) -> 221fr2y11ebk4cog84wok which is exactly I want.
  • However in ie11 the string result is 6.936gwtrpf69(e+20).

How can I get the same string 221fr2y11ebk4cog84wokfrom 8.357963780872523e+31 in a cross browser manner?

BTW: I got the idea of this random string from this thread: Random alpha-numeric string in JavaScript?

Share Improve this question edited May 23, 2017 at 10:29 CommunityBot 11 silver badge asked Sep 17, 2015 at 8:26 nacho4dnacho4d 45.2k47 gold badges163 silver badges246 bronze badges 3
  • What does .toFixed(20) mean ? – nacho4d Commented Sep 17, 2015 at 8:34
  • Do you need fixed number of characters, always? – sinisake Commented Sep 17, 2015 at 9:01
  • not really. I just want to reduce possibilities of conflict with other external random id generators (I don't know what algorithms are used) – nacho4d Commented Sep 17, 2015 at 9:04
Add a ment  | 

2 Answers 2

Reset to default 3

Keeping in mind that Math.random() returns a value between 0 and 1 (exclusive), and that numbers in JavaScript have 53 bits mantissa as per IEEE-754, a safe way to get a random integer would be

Math.random() * Math.pow(2, 54)

So a random alphanumeric string could be obtained from

(Math.random() * Math.pow(2, 54)).toString(36)

Note that there is no guarantee about the number of characters, which could be anything between 1 and 11 depending on the order of magnitude of the random value.

As fas as I can see, you don't need to multiply the random number by such a large number. Try this:

Math.random().toString(36).slice(2)

Does that suffice? It's a slightly shorter string but it's consistent in all browsers (that I tested).

发布评论

评论列表(0)

  1. 暂无评论