Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a random string of letters and numbers in Javascript? [duplicate]

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

like image 530
Chuck Norris Avatar asked Nov 27 '22 00:11

Chuck Norris


1 Answers

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

like image 101
Antony Avatar answered Dec 10 '22 01:12

Antony