How To Create A Random String With Maximum Characters in JavaScript

Create your own random data generator in JavaScript!

Dev By RayRay's photo
Dev By RayRay
ยทJan 26, 2022ยท

2 min read

How To Create A Random String With Maximum Characters in JavaScript

Photo by Aditya Saxena on Unsplash

Play this article

You can use a library for generating random data in JavaScript, but I think it's even cooler to do it yourself. If you want to spice up your JavaScript skills, these functions are the best to practice.

So in this post, I would like to explain how you can generate random strings with a maximum amount of characters. This post is a follow-up to my previous post How To Create a Random String with JavaScript.

Originally published on


If you haven't checked my previous post, I highly recommend checking it out. In this, we will continue with that last function from that post.

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

This function now generates a random string with a variable length.

The return value is always different.


But right now, we want to make sure that it has a certain length so we have more control over the data we generate.

We only have to make sure that the Array it's starting with has the length.

Minimal length

To make sure we have at least the number of characters we are given in the function parameter, we are making the Array a bit longer.

[...Array(length + 10)]

Fixed length

But to prevent that will be longer, we are taking a substring, so we are returning the exact amount of characters by using substring.

[...Array(length + 10)].map((value) => (Math.random() * 1000000).toString(36).replace('.', '')).join('').substring(0, length);

If we turn all of this into a function, this would be our result.

function randomString(length = 50) {
    return [...Array(length + 10)].map((value) => (Math.random() * 1000000).toString(36).replace('.', '')).join('').substring(0, length);

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

The next post will be another JavaScript exercise ๐Ÿ˜‰.


Thanks for reading!


I 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 on Hashnode.

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 ๐Ÿ˜

Did you find this article valuable?

Support Dev By RayRay by becoming a sponsor. Any amount is appreciated!

See recent sponsors |ย Learn more about Hashnode Sponsors
Share this