jQuery Data Type How to - Generate a random string of letters and numbers








Question

We would like to know how to generate a random string of letters and numbers.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--from  www  . j  a  v  a  2  s  .com-->
function stringGen(len)
{
    var text = " ";
    var charset = "abcdefghijklmnopqrstuvwxyz0123456789";
    for( var i=0; i < len; i++ )
        text += charset.charAt(Math.floor(Math.random() * charset.length));
    return text;
}
document.writeln(stringGen(3));
document.writeln('<br/>');
document.writeln(stringGen(3));
document.writeln('<br/>');
document.writeln(stringGen(3));
document.writeln('<br/>');
document.writeln(stringGen(3));

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: