我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
非常简单
function getRandomColor(){
var color='';
while(color.length<6){
color=Math.floor(Math.random()*16777215).toString(16);
}
return '#'+color;
}
其他回答
我没有找到支持小写和大写字符的干净解决方案。
仅小写支持:
Math.random().toString(36).substr(2,5)
基于该解决方案,支持小写和大写:
Math.random().toString(36).substr(2,5).split(“”).map(c=>Math.randm()<0.5?c.toUpperCase():c).jjoin(“”);
更改substr(2,5)中的5以调整到所需的长度。
通过回答Gertas和Dragon提出的问题,扩展Doubletap的优雅示例。只需添加一个while循环来测试那些罕见的空情况,并将字符限制为五个。
function rndStr() {
x=Math.random().toString(36).substring(7).substr(0,5);
while (x.length!=5){
x=Math.random().toString(36).substring(7).substr(0,5);
}
return x;
}
这里有一个jsfiddle提示您一个结果:http://jsfiddle.net/pLJJ7/
在下面的代码中,我正在生成8个字符的随机代码
function RandomUnique(){
var charBank = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789";
var random= '';
var howmanycharacters = 8;
for (var i = 0; i < howmanycharacters ; i++) {
random+= charBank[parseInt(Math.random() * charBank.lenght)];
}
return random;
}
var random = RandomUnique();
console.log(random);
这是肯定的
<script language="javascript" type="text/javascript">
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 8;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
document.randform.randomfield.value = randomstring;
}
</script>
您可以使用Web Crypto的API:
console.log(self.crypto.getRandomValues(新Uint32Array(1))[0])
(此处为原始答案)