Ola Ola - 1 year ago 74
Javascript Question

Generate short unique ID of 6 to 9 characters in Javascript

I need to create a unique id which I can assign to a user
it needs to be between 6 and 9 characters
it can be alphanumeric
I have seen this answer
Random alpha-numeric string in JavaScript?

but it generates long ID, I want the ID to be between 6 and 9 characters

How can achieve this in javascript?

Answer Source

//Generating random
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
//Generating unique id
function id(n){
  var char = "";
  for(let i = 0;i<n;i+=1){
    char += String.fromCharCode(getRandomInt(32, 100));//alphanumeric chars
  }
  return char;
}
//test
for(let i=0;i<10;i+=1){
  var uniqueId = id(getRandomInt(6,9));//between 6 and 9 characters
  //result
  console.log(uniqueId, uniqueId.length);
}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download