Generate random string/characters in JavaScript

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

    The simplest way is:

    (new Date%9e6).toString(36)
    

    This generate random strings of 5 characters based on the current time. Example output is 4mtxj or 4mv90 or 4mwp1

    The problem with this is that if you call it two times on the same second, it will generate the same string.

    The safer way is:

    (0|Math.random()*9e6).toString(36)
    

    This will generate a random string of 4 or 5 characters, always diferent. Example output is like 30jzm or 1r591 or 4su1a

    In both ways the first part generate a random number. The .toString(36) part cast the number to a base36 (alphadecimal) representation of it.

提交回复
热议问题