In this article we will see how to generate a random hash string using javascript.

Here are the different hash strings that we will see how to generate.

  • "alnum": includes all lowercase and uppercase letters and digits
  • "alpSpecLower": includes lowercase letters, hyphens, and underscores
  • "alpha": includes all lowercase and uppercase letters
  • "alpNumLower": includes lowercase letters and digits
  • "hexdec": includes hexadecimal digits (0-9, a-f)
  • "numeric": includes digits only
  • "nozero": includes digits 1-9 only

Following is the example on how to generate the random hash string using javascript.

function randomHash(format, length) {
  let pool = "";

  switch (format) {
    case "alnum":
      pool = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
      break;
    case "alpSpecLower":
      pool = "abcdefghijklmnopqrstuvwxyz-_";
      break;
    case "alpha":
      pool = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
      break;
    case "alpNumLower":
      pool = "0123456789abcdefghijklmnopqrstuvwxyz";
      break;
    case "hexdec":
      pool = "0123456789abcdef";
      break;
    case "numeric":
      pool = "0123456789";
      break;
    case "nozero":
      pool = "123456789";
      break;
    default:
      return "";
  }

  let buf = "";

  for (let i = 0; i < length; i++) {
    buf += pool.charAt(Math.floor(Math.random() * pool.length));
  }

  return buf;
}

console.log("alnum :", randomHash("alnum", 10));
console.log("alpSpecLower :", randomHash("alpSpecLower", 10));
console.log("alpha :", randomHash("alpha", 10));
console.log("alpNumLower :", randomHash("alpNumLower", 10));
console.log("hexdec :", randomHash("hexdec", 10));
console.log("numeric :", randomHash("numeric", 10));
console.log("nozero :", randomHash("nozero", 10));

In the above example, we defined a function called randomHash that takes two parameters: format and length. The format parameter specifies the format of the hash string, while the length parameter specifies the length of the hash string.

We use a switch statement to select the appropriate character pool based on the format, and generate a random string by selecting characters from the pool using the charAt() method.

We then call the randomHash function with different format and length parameters to get the random hash string of the specified length.

Categorized in:

Tagged in: