Generate random string/characters in JavaScript

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

    let r = Math.random().toString(36).substring(7);
    console.log("random", r);

    Note: The above algorithm has the following weaknesses:

    • It will generate anywhere between 0 and 6 characters due to the fact that trailing zeros get removed when stringifying floating points.
    • It depends deeply on the algorithm used to stringify floating point numbers, which is horrifically complex. (See the paper "How to Print Floating-Point Numbers Accurately".)
    • Math.random() may produce predictable ("random-looking" but not really random) output depending on the implementation. The resulting string is not suitable when you need to guarantee uniqueness or unpredictability.
    • Even if it produced 6 uniformly random, unpredictable characters, you can expect to see a duplicate after generating only about 50,000 strings, due to the birthday paradox. (sqrt(36^6) = 46656)

提交回复
热议问题