DEV Community

Niklas
Niklas

Posted on • Edited on • Originally published at niklasmtj.de

4 2

Generate a random hash with fixed length

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!

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs