SkinneQ
SkinneQ

Reputation: 13

Key Generator - JavaScript, License key

I have a question, how can I do this 1234-5678-9123-4567. I mean the "-" every 4 numbers.

function makeid(length) {
  var result = [];
  var characters = '0123456789';
  var charactersLength = characters.length;
  for (var i = 0; i < length; i++) {
    result.push(characters.charAt(Math.floor(Math.random() *
      charactersLength)));
  }
  return result.join('-');
}
console.log(makeid(16))

Upvotes: 1

Views: 2209

Answers (3)

Som Shekhar Mukherjee
Som Shekhar Mukherjee

Reputation: 8188

You can do this by adding some simple conditional logic.

NOTE: The code assumes that length of the id is a multiple of 4 because I've stripped of the last character assuming it will always be a dash.

function makeid(length) {
  const characters = "0123456789";
  const result = Array.from({ length })
    .map(
      (e, i) =>
        characters[Math.floor(Math.random() * characters.length)] +
        (!((i + 1) % 4) ? "-" : "")
    )
    .join("")
    .slice(0, -1);
  return result;
}

console.log(makeid(16));

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386720

You could take Array.from for creating an array with the wanted length and replace the parts with dash.

function makeid(length) {
    const characters = '0123456789';
    return Array
        .from(
            { length },
            _ => characters[Math.floor(Math.random() * characters.length)]
        )
        .join('')
        .replace(/....(?=.)/g, '$&-');
}

console.log(makeid(10));

Upvotes: 0

Wais Kamal
Wais Kamal

Reputation: 6180

Put the characters you want to use in a string, then match every four characters and join your matches with dashes:

function makeid(length) {
  var result = "";
  var characters = '0123456789';
  for (var i = 0; i < length; i++) {
    result += characters[Math.floor(Math.random() * characters.length)];
  }
  result = result.match(/\d{1,4}/g).join("-");
  return result;
}

console.log(makeid(16));

Upvotes: 2

Related Questions