7

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

2
  • You never define len Commented Apr 19, 2013 at 14:15
  • If you are using Lodash or Underscore, then stackoverflow.com/questions/1349404/… Commented Apr 20, 2016 at 5:44

4 Answers 4

33

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".

Sign up to request clarification or add additional context in comments.

1 Comment

+1 This one looks more correct than mine as it allows you to define the length of the string you need.
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);

}

5 Comments

The maximum length is 11 and, depending on the random number generated, sometimes you get 10 characters instead.
Yea that's true, good point :)
Now fixed for "unlimited" length.
If conciseness was your aim, you could put the var rdmString = "" into the first part of the for loop
Instead of substring, you can better use "slice()". For eg, Math.random().toString(34).slice(2);
2

Just as alternative:

var len = 20,
    str = '';

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

console.log( str );

2 Comments

This is more than alphanumeric. Anyway the OP must have copied the function somewhere.
@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.
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/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.