How To Generate Random String/Characters In JavaScript.

AuthorSumit Dey Sarkar

Pubish Date26 Aug 2022

categoryJavaScript

In this article we will see how to generate random string/characters in JavaScript.

Here we will pass length of string and we will also use Math.random().

Let's see example -

How to generate random string/characters in JavaScript

<html>

<head>
  <title>How to generate random string/characters in JavaScript</title>
</head>

<body>
  <button type="button" onClick="alert(randomString(10))">Create Random String</button>
</body>

<script type="text/javascript">

  function randomString(length) {
    var text = "";
    var possibleChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < length; i++)
      text += possibleChar.charAt(Math.floor(Math.random() * possibleChar.length));

    return text;
  }

</script>
Comments 0

Leave a comment