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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *