js随机(数字/字母/混合)字符串


<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<form action="" method="get" name="form1">
字符串长度<input name="len" type="text" value="6" size="2" maxlength="2">
字符串数量<input name="count" type="text" value="18" size="2" maxlength="2"><br><br>
<input name="lower" type="checkbox" checked>小写字母  
<input name="upper" type="checkbox">大写字母  
<input name="num" type="checkbox">数字
<br><br>
<textarea name="content" style="width:100%;" rows="9"></textarea>
</form>

<script type="text/javascript">
function rnd_i(lbound, ubound) {
    var x=Math.random() * (ubound - lbound);
    return (Math.floor(x) + lbound);
}

function rnd_str(len) {
    var num = "0123456789";
    var lower = "abcdefghijklmnopqrstuvwxyz";
    var upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var str='';
    if(form1.num.checked){
        str+=num;
    }
    if(form1.lower.checked){
        str+=lower;
    }
    if(form1.upper.checked){
        str+=upper;
    }
    var temp='';
    var i=0;
    for(var n=0;n<form1.len.value;n++){
        i=rnd_i(0, str.length);
        temp += str.charAt(i);
    }
    return temp;
}

function main(){
    var temp='';
    for(var i=0;i<form1.count.value;i++){
        temp += (rnd_str(6)+',');
    }
    form1.content.value=temp;
}
</script>
<input onClick="main()" value="随机生成" type="button">

程序运行结果如下图所示,点击这里亲自运行看看