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!

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

nextjs tutorial video

📺 Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay