aianLee
aianLee

Reputation: 61

random with 8 alphanumeric characters

I have a system that needs to generate random number to serve as a reference number. Here's what i used in JavaScript:

        function random() {
            return Math.floor(Math.random() * 100000000);
        }

This works fine but I need the random number to be 8 chars long. This code generates 8-characters long number, but there are instances that it only generates 7 digits.

And also, is it possible that the "random number" can be alphanumeric? thanks

Upvotes: 0

Views: 461

Answers (3)

Mathi
Mathi

Reputation: 762

Try This:

function randomString()
{
var chars ="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var result = '';
for (var i = 8; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
return result;
}
var radomNumber = randomString();

Upvotes: 1

Amit
Amit

Reputation: 15387

Try This

function randomString(length, chars) {
  var mask = '';
  if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
  if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  if (chars.indexOf('#') > -1) mask += '0123456789';
  if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\';
  var result = '';
  for (var i = length; i > 0; --i) 
     result += mask[Math.round(Math.random() * (mask.length - 1))];
  return result;
}

document.write(randomString(8, '#aA'));

Demo

Upvotes: 3

웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

function makeid()
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

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

    return text;
}

Upvotes: 0

Related Questions