Create a Username from a String in JavaScript

ยท

4 min read

In today's world, almost every website or application requires a username to be unique for every user. A username is an identifier for a user to login or access a website or application. However, generating a unique username from a string can be challenging. In this blog, we will discuss how to generate a username from a string using JavaScript.

Let's start by understanding what we mean by a string. In JavaScript, a string is a collection of characters enclosed within single or double quotes. For example, "Hello World!" is a string.

To generate a username from a string, we need to first remove any unnecessary characters such as whitespace, punctuation marks, or special characters. We will keep only letters, numbers, and underscores. We can achieve this by using the power of regular expressions and some super-cool JavaScript code snippets! ๐ŸŽ‰. Regular expressions are patterns that match one or more characters in a string.

Here is an example :

const convertToUsername = (Text) => {
  let username = Text.toLowerCase()
    .replace(/[^\w ]+/g, '')
    .replace(/ +/g, '_')
    .replace(/_+/g, '_');

  let lastChar = username.slice(-1);

  if (lastChar === '_') {
    username = username.substring(0, username.length - 1);
  }

  return username;
};

The above code defines a function named convertToUsername that takes a Text parameter and returns a username based on the provided text. Let's go through the code step by step to understand what it does:

  1. The Text parameter is converted to lowercase using the toLowerCase() method to ensure consistency in the username.
let username = Text.toLowerCase()
  1. The next line replaces any non-alphanumeric characters with an empty string using a regular expression [^\w ]+. This ensures that only letters, numbers, and spaces are included in the username.
.replace(/[^\w ]+/g, '')
  1. The next line replaces any consecutive spaces with a single underscore character. This is done to ensure that the username is readable and does not have multiple spaces in a row.
.replace(/ +/g, '_')
  1. The final line replaces any consecutive underscores with a single underscore character. This is done to ensure that the username is readable and does not have multiple underscores in a row.
.replace(/_+/g, '_');
  1. The next line checks if the last character of the username is an underscore character. If it is, it removes the underscore character from the end of the username.
let lastChar = username.slice(-1);

if (lastChar === '_') {
  username = username.substring(0, username.length - 1);
}
  1. The function then returns the final username.
return username;

Overall, the convertToUsername function ensures that the generated username is readable and contains only alphanumeric characters and underscores. This function can be useful for generating usernames from user inputs or other text-based inputs.

Yo, hold up! We ain't done yet. The username might not be unique, ya know? Like, if it's already in the database or something. So, we gotta add some more JavaScript code to sort that out.

const generateUniqueUsername = (data) => {
  const convertedUsernameStr = convertToUsername(data);
   //It will check if the username exists in the db or not
  const result = await checkUserNameExist(convertedUsernameStr);

  //If already available with the same name then generate a unique new one
  if (result) {
    return convertedUsernameStr + '_' + Math.random().toString(36).substr(2, 5);
  }
  //else convert to username string
  return convertedUsernameStr;
};

The above code defines a function named generateUniqueUsername that takes a data parameter and generates a unique username based on the provided data. Let's go through the code step by step to understand what it does:

  1. The function first calls the convertToUsername function and passes the data parameter to it. The convertToUsername function converts the data to a username string based on the rules defined in the function.
const convertedUsernameStr = convertToUsername(data);
  1. The function then calls the checkUserNameExist function to check if the generated username already exists in the database. This function is not defined in the given code, but it can be assumed that it returns a boolean value indicating whether the username already exists in the database or not.
const result = await checkUserNameExist(convertedUsernameStr);
  1. If the checkUserNameExist function returns true, indicating that the username already exists in the database, the function generates a unique new username by appending a random string to the end of the original username.
if (result) {
  return convertedUsernameStr + '_' + Math.random().toString(36).substr(2, 5);
}
  1. If the checkUserNameExist function returns false, indicating that the username does not exist in the database, the function simply returns the original username that was generated by the convertToUsername function.
return convertedUsernameStr;

Overall, the generateUniqueUsername function generates a unique username by first converting the provided data to a username string, checking if the username already exists in the database, and appending a random string to the end of the original username if it already exists. This function can be useful for ensuring that usernames generated from user inputs are unique and do not clash with existing usernames in the database.

ย