-2

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?

Ola
  • 431
  • 1
  • 8
  • 28

2 Answers2

4

//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);
}
alessandrio
  • 4,282
  • 2
  • 29
  • 40
1

What you could do is to define an array of all allowed characters. Afterwards you loop over it as often your ID needs to be long. (Already posted by @Thomas Juranek)

Main issue here: how can be confirmed that it's unique? What is memorable? Do you have a storage were all used IDs are in (database, file, etc.)?

Another approach would be much more complicated: Combine parts of (fe. your MAC address) and a current timestamp. You can hash it to disguise the reference of this data.

But it mainly depends on your use case. Maybe this one gives you also a spin

da-chiller
  • 156
  • 1
  • 13