如果我想创建一个含有数字、字母(大小写)或者符号的字符串,比如从[a-zA-Z0-9]集合中中创建一个随机的字符串,长度为5.有没有什么比较好的代码呢?本文提供了几种方法,包括自动改变字符集合。
第一种:
//code from https://qdkfweb.cn/js-random-string.html
function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
第二种:不需要输入字符集合
function randomstring(L){
var s= '';
var randomchar=function(){
var n= Math.floor(Math.random()*62);
if(n<10) return n; //1-10
if(n<36) return String.fromCharCode(n+55); //A-Z
return String.fromCharCode(n+61); //a-z
}
while(s.length< L) s+= randomchar();
return s;
}
alert(randomstring(5))
第三种:支持自定义字符长度和特征字符集合
function randomString(len, charSet) {
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var randomString = '';
for (var i = 0; i < len; i++) {
var randomPoz = Math.floor(Math.random() * charSet.length);
randomString += charSet.substring(randomPoz,randomPoz+1);
}
return randomString;
}
Call with default charset [a-zA-Z0-9] or send in your own:
var randomValue = randomString(5);
var randomValue = randomString(5, 'PICKCHARSFROMTHISSET');