xxvii-jauregui
xxvii-jauregui

Reputation: 39

Generating a unique ID in javascript (firstmiddlelastname)

Can anyone help me on how to generate an user Id by using the first character of the first name and first character of middle name combined together with the last name with 4 numbers? All the information above is filled in into a form.

Upvotes: 0

Views: 340

Answers (2)

shotor
shotor

Reputation: 1062

Assuming you have the first and last name, you can generate a random number and concatenate the values together.

For the random part we can use the Math.random function to generate a 4 digit number. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

To get the first character wen use the charAt function that is available on all strings. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt

    var firstname = 'John'
    var lastname = 'Doe'
    var random = Math.floor(1000 + Math.random() * 9000) // 4 digit random number

    // charAt(0) will give the first character in the string
    var userid = firstname.charAt(0) + lastname + random
    console.log(userid); // Example: "JDoe1234"

Upvotes: 1

Blindman67
Blindman67

Reputation: 54089

I prefer to use a list or string of characters to randomly select from to generate ids

const digits = "0123456789";
function createID(firstName,lastName,charCount = 4){
    var id = firstName[0] + lastName;
    while(charCount--){ id += digits[(Math.random() * digits.length) | 0] }
    return id;
}

console.log(createID("Blind","Man"));

Upvotes: 0

Related Questions