HomeAboutBlog

Generate a random hash with fixed length

28 November, 2019 - 1 min read

In one of my projects I’ve been working on lately I needed the opportunity to create random hashes. One day I found a simple method that does just that at work in PHP and translated it quickly to JavaScript to use it in my project.

The following code will create you a n-sized hash with random letters and numbers. To set the hash length set the i-condition in the for loop. For possible reasons of confusion there is no O(bvious) in the characters string. If you need you can add small letters or special characters to the string to generate more complex hashes.

generateRandomHash() {
    const characters = "0123456789ABCDEFGHIJKLMNPQRSTUVWXYZ";
    let string = "";
    for (let i = 0; i <= HASHLENGTH; i++) {
      string += characters[Math.floor(Math.random() * characters.length)];
    }
    return string;
  }