DEV Community

loading...

Generate a random hash with fixed length

niklasmtj profile image Niklas Originally published at niklasmtj.de Updated on ・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;
  }
Enter fullscreen mode Exit fullscreen mode

You can find this and more posts on my blog niklasmtj.de

Thanks for reading!

Discussion (0)

Forem Open with the Forem app