I’ll demonstrate how to create random characters or strings in javascript in this example. For a token or other purpose, we can easily create a random alphanumeric string using jQuery.
We need to write a custom JS function to produce random and unique strings in javascript since neither jquery nor javascript offer a built-in random string generator. We will supply the string’s length, and it will output a random string. We’ll also employ the Math.random() function.
You should look at the example below. You can also run the html file below to observe the outcomes. Also included is a demo.
Example:
<html>
<head>
<title>How to generate random string in javascript?</title>
</head>
<body>
<input type="button" value="Create Random String" onClick="alert(generateRandomString(10))">
</body>
<script type="text/javascript">
function generateRandomString(length) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < length; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
</script>
</html>

I’m Abhishek, a DevOps, SRE, DevSecOps, and Cloud expert with a passion for sharing knowledge and real-world experiences. I’ve had the opportunity to work with Cotocus and continue to contribute to multiple platforms where I share insights across different domains:
-
DevOps School – Tech blogs and tutorials
-
Holiday Landmark – Travel stories and guides
-
Stocks Mantra – Stock market strategies and tips
-
My Medic Plus – Health and fitness guidance
-
TrueReviewNow – Honest product reviews
-
Wizbrand – SEO and digital tools for businesses
I’m also exploring the fascinating world of Quantum Computing.
[…] https://www.devopsconsulting.in/blog/generate-random-string-in-javascript/ […]