Generate Random String in Javascript

Posted by

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