DEV Community

Dev By RayRay
Dev By RayRay

Posted on β€’ Originally published at hasnode.byrayray.dev on

How To Create a Random String with JavaScript

Cover picture

For many purposes, you can need a random string. Sometimes a long one and sometimes a short one. A lot of time, I use these functions in a unit or end-to-end test to automate even more.

In this post, I will show you how you can create it yourself; I will explain every part of the function to extend it yourself.

Enjoy the ride!

divider-byrayray.png

Get a random number

In JavaScript, we have a Math Object with all kinds of mathematical constants and functions. You need Math.random() when you want to create random things. This will return a random float. (Try it in your console). The result of this function is always higher than 0 and lower than 1.

Math.random()
Enter fullscreen mode Exit fullscreen mode

But since we want to generate a short random string, we don't need a number in the first place. By multiplying the result of Math.random() * 10 you will get a number between 1 and not higher than 10. Our result could be 5.698829761336681 or something like that.

Math.random() * 10 
// returns 5.698829761336681
Enter fullscreen mode Exit fullscreen mode

So how do we turn this into a string? Pretty simple, if you put .toString(36) behind this, you will get a string with numbers and letters with a dot in between. With the number 36 as a parameter in the .toString() method, you apply a base 36 encoding on the string.

(Math.random() * 10).toString(36); 
// returns '9.ja773x85wr'
Enter fullscreen mode Exit fullscreen mode

Every time you run this code, it will be different. If you want to remove the dot, then replace it like this.

(Math.random() * 10).toString(36).replace('.', ''); 
// returns '1cq54mxwg9hl'
Enter fullscreen mode Exit fullscreen mode

Now that you have generated a random string every time you run it, you can turn it into a function.

function randomString() {
    return (Math.random() * 1000000).toString(36).replace('.', '');
}
Enter fullscreen mode Exit fullscreen mode

What are you want to have a longer string? Well, you can create a loop and turn that into a string again.

function randomString() {
    return [...Array(5)].map((value) => (Math.random() * 1000000).toString(36).replace('.', '')).join('');
}

// returns '8mtmvtuzzfnau0bf0ecy668tzrc3ztc57a7b87vehyu51yb8gj35t7'
Enter fullscreen mode Exit fullscreen mode

I would recommend playing around with this function and using it for something practical.

The next post will be another JavaScript exercise πŸ˜‰

divider-byrayray.png

Thanks!

hashnode-footer.pngI hope you learned something new or are inspired to create something new after reading this story! πŸ€— If so, consider subscribing via email (scroll to the top of this page) or follow me here.

Did you know that you can create a Developer blog like this one, yourself? It's entirely for free. πŸ‘πŸ’°πŸŽ‰πŸ₯³πŸ”₯

If I left you with questions or something to say as a response, scroll down and type me a message. Please send me a DM on Twitter @DevByRayRay when you want to keep it private. My DM's are always open 😁

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay