第一种:
//code from http://caibaojian.com/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');
演示截图
以上就是javascript创建含数字字母的随机字符串的三种方法总结,有需要的可以参考学习。
更多javascript创建含数字字母的随机字符串。