Categories
JavaScript Answers

How to generate random string for div ID with JavaScript?

Spread the love

Sometimes, we want to generate random string for div ID with JavaScript.

In this article, we’ll look at how to generate random string for div ID with JavaScript.

How to generate random string for div ID with JavaScript?

To generate random string for div ID with JavaScript, we can create a random base64 string.

To do this, we write

const id = btoa(Math.random()).substring(0, 12);

to call Math.random to create a random number between 0 and 1.

Then we call btoa on the returned number to convert it to a base64 string.

Next, we call substring with 0 and 12 to return a string with the first 12 characters of the base64 string.

Conclusion

To generate random string for div ID with JavaScript, we can create a random base64 string.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.