Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours scrolling social media and waste money on things we forget, but won’t spend 30 minutes a day earning certifications that can change our lives.
Master in DevOps, SRE, DevSecOps & MLOps by DevOps School!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

Generate Random String in Javascript

JavaScript

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>
0 0 votes
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
1
0
Would love your thoughts, please comment.x
()
x