Generate random string/characters in JavaScript

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

    Here are some easy one liners. Change new Array(5) to set the length.

    Including 0-9a-z

    new Array(5).join().replace(/(.|$)/g, function(){return ((Math.random()*36)|0).toString(36);})
    

    Including 0-9a-zA-Z

    new Array(5).join().replace(/(.|$)/g, function(){return ((Math.random()*36)|0).toString(36)[Math.random()<.5?"toString":"toUpperCase"]();});
    

提交回复
热议问题