6

I have been using this code:

function stringGen()
{
    var text = " ";

    var charset = "abcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < len; i++ )
        text += charset.charAt(Math.floor(Math.random() * charset.length));

    return text;
}

But so far, it has not been working, like at all. What am I doing wrong?

Thank you for your help in advance

techfoobar
  • 65,616
  • 14
  • 114
  • 135
Chuck Norris
  • 71
  • 1
  • 2
  • 5
  • You never define `len` – m90 Apr 19 '13 at 14:15
  • If you are using `Lodash` or `Underscore`, then http://stackoverflow.com/questions/1349404/generate-a-string-of-5-random-characters-in-javascript/36734713#36734713 – vineet Apr 20 '16 at 05:44

4 Answers4

31

You missed the parameter len.

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;
}

console.log(stringGen(3));

This would give you something like "a1z".

Antony
  • 14,900
  • 10
  • 46
  • 74
10

A pretty one-liner would be:

Math.random().toString(36).substr(2, length)

Or if you need a str that is longer than 10/11 characters:

function generateRandAlphaNumStr(len) {
  var rdmString = "";
  for( ; rdmString.length < len; rdmString  += Math.random().toString(36).substr(2));
  return  rdmString.substr(0, len);

}
robahl
  • 559
  • 1
  • 6
  • 13
2

Just as alternative:

var len = 20,
    str = '';

while( len-- ) {
    str += String.fromCharCode( 48 + ~~(Math.random() * 42) );
}

console.log( str );
jAndy
  • 231,737
  • 57
  • 305
  • 359
  • This is more than alphanumeric. Anyway the OP must have copied the function somewhere. – Antony Apr 19 '13 at 14:24
  • @Antony true, I was a little lazy. To get pure alpha nummericals we would need to limit the ascii range more. However, I felt like this is a more generic approach as having a pre-defined map of characters. – jAndy Apr 19 '13 at 14:27
1

Your len variable is undefined. Either pass it in as a parameter, or set it to something.

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;
}
alert(stringGen(5));

http://jsfiddle.net/rg7Z3/

SteveP
  • 18,840
  • 9
  • 47
  • 60