我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
最重要的是,所有的答案都是完美的。但我要补充的是,生成任何随机字符串值都非常好而且快速
函数randomStringGenerator(stringLength){var randomString=“”;//选择变量的空值const allCharacters=“`~!@#$%^&*()_+-={}[]:;\'<>?,./|\\ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijlmnopqrstuvwxyz0123456789'”;//所有字母数字字母列表while(stringLength--){randomString+=allCharacters.substr(Math.floor((Math.random()*allCharacters.length)+1),1);//使用Math.random()从所有字符变量中选择任意值}return randomString;//返回生成的字母数字字符串}console.log(randomStringGenerator(10))//通过输入所需的随机字符串来调用函数
or
console.log(Date.now())//它每次都会产生随机的十三个数字字符值。console.log(Date.now().toString().length)//打印生成字符串的长度
其他回答
我想这会对你有用:
函数makeid(长度){let result=“”;const characters=‘EFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789’;常量字符长度=字符长度;让计数器=0;while(计数器<长度){result+=characters.charAt(Math.floor(Math.random()*charactersLength));计数器+=1;}返回结果;}console.log(makeid(5));
最紧凑的解决方案,因为切片比子字符串短。从字符串末尾减去允许避免由随机函数生成的浮点符号:
Math.random().toString(36).slice(-5);
甚至
(+new Date).toString(36).slice(-5);
更新:添加了一种使用btoa方法的方法:
btoa(Math.random()).slice(0, 5);
btoa(+new Date).slice(-7, -2);
btoa(+new Date).substr(-7, 5);
//使用Math.random和Base 36:console.log(Math.random().toString(36).slice(-5));//使用新的日期和基数36:console.log((+new Date).toString(36).slice(-5));//使用Math.random和Base 64(btoa):console.log(btoa(Math.random()).slice(0,5));//使用新的日期和基数64(btoa):console.log(btoa(+新日期).slice(-7,-2));console.log(btoa(+新日期).substr(-7,5));
const c = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
const s = [...Array(5)].map(_ => c[~~(Math.random()*c.length)]).join('')
以下是CoffeeScript中的示例:
String::add_Random_Letters = (size )->
charSet = 'abcdefghijklmnopqrstuvwxyz'
@ + (charSet[Math.floor(Math.random() * charSet.length)] for i in [1..size]).join('')
可以使用
value = "abc_"
value_with_exta_5_random_letters = value.add_Random_Letters(5)
这是我创建的方法。它将创建一个包含大小写字符的字符串。此外,我还包含了将创建字母数字字符串的函数。
工作示例:http://jsfiddle.net/greatbigmassive/vhsxs/(仅限alpha)http://jsfiddle.net/greatbigmassive/PJwg8/(字母数字)
function randString(x){
var s = "";
while(s.length<x&&x>0){
var r = Math.random();
s+= String.fromCharCode(Math.floor(r*26) + (r>0.5?97:65));
}
return s;
}
2015年7月升级这做了同样的事情,但更有意义,包括所有字母。
var s = "";
while(s.length<x&&x>0){
v = Math.random()<0.5?32:0;
s += String.fromCharCode(Math.round(Math.random()*((122-v)-(97-v))+(97-v)));
}