How to create a password generator - JavaScript?


These days, password generators can be found all over the internet. Without a strong enough password, websites frequently won't let you establish an account. The task we are going to perform was how to create a password generator JavaScript.

Let’s dive into the article for getting better understanding on creating a password generator. For this, use Math.random() to create random passwords.

Using Math.random() method

A floating-point pseudo-random number in the range [0,1], 0 (inclusive), and 1(exclusive) is returned by the JavaScript function Math.random(). You can then resize this random number to fit the necessary range.

Syntax

Following is the syntax for Math.random()

Math.random()

For getting more idea on creating a password generator, let’s look into the following examples.

Example

In the following example, we are running the script using Math.random() to generate a random password, and we are limiting the random password to 4 digits.

<!DOCTYPE HTML>
<html>
   <body style="text-align:center;background-color:#EAFAF1;">
      <h3>
         Click to Generate Random Passwords
      </h3>
      <button onclick="changepassword()">
         Click Here
      </button>
      <br>
      <div>
         <p id="tutorial"></p>
      </div>
      <script>
         var element_down = document.getElementById("tutorial");
         function passwordgenerator() {
            var pass = '';
            var str = 'WelcomeToTheTutorialsPoint' +
            'qujzkexlxwlkcewxmxekhnexj@#$';
            for (let i = 1; i <= 4; i++) {
               var char = Math.floor(Math.random()
               * str.length + 1);
               pass += str.charAt(char)
            }
            return pass;
         }
         function changepassword() {
            element_down.innerHTML = passwordgenerator();
         }
      </script>
   </body>
</html>

When the script gets executed, it will generate an output consisting of text along with a click button. When the user clicks the button, an event occurs that generates a 4-digit random password each time the button is clicked.

Example

Consider the following example, here we are running the script using Math.random() to generate a random password based on the length of the user's input.

<!DOCTYPE HTML>
<html>
   <body style="text-align:center;background-color:#E8DAEF;">
      <input type="text" id="digitspassword" oninput="generatepassword()" placeholder="Use Single Digits(0-9)"/>
      <p id="tutorial"></p>
      <script>
      function generatepassword(){
         var inputlength=document.getElementById('digitspassword');
         var UserInput=inputlength.value.replace(/[^0-9.]/g, "");
         inputlength.value=UserInput;
         var Results=document.getElementById('tutorial');
         var text = "";
         var shuffle = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
         if(inputlength!==''){
            for( var i=0; i < inputlength.value; i++ ){
               text += shuffle.charAt(Math.floor(Math.random() * shuffle.length));
            }
            Results.innerHTML=text;
         }
      }
      </script>
   </body>
</html>

On running the above script, the output window will pop up, displaying the input field for the user to enter the input along with a placeholder text inside the input field. When the user enters the number, it will generate a random password based on the user's entered number.

Example

Execute the below script and observe how we are generating the password randomly and how we are using the two buttons, one to generate and one to copy.

<!DOCTYPE HTML>
<html>
   <body>
      <style>
      #button {
         font-size: 18px;
         margin-top: 15px;
         width: 100px;
         height: 50px;
         text-align: center;
         background-color: #ABEBC6 ;
         display: flex;
         color: rgb(23, 32, 42);
         justify-content: center;
         align-items: center;
         cursor: pointer;
         border-radius: 5px;
      }
      </style>
      <h2>Generate Password Randomly</h2>
      <input type="text" name="" placeholder="Create password" id="tutorial" readonly>
      <table>
         <th><div id="button" onclick="generatepassword()">Generate</div></th>
         <th><a id="button" onclick="passwordcopy()">Copy</a></th>
      </table>
      <script>
         var password=document.getElementById("tutorial");
         function generatepassword() {
            var chars = "01239abcdefghijABCDEF45678GHIJKLMNOPQRSTUVWXYZklmnopqrstuvwxyz!@#$%^&*()";
            var passwordLength = 5;
            var password = "";
            for (var i = 0; i <= passwordLength; i++) {
               var randomNumber = Math.floor(Math.random() * chars.length);
               password += chars.substring(randomNumber, randomNumber +1);
            }
            document.getElementById("tutorial").value = password;
         }
         function passwordcopy() {
            var copyText = document.getElementById("tutorial");
            copyText.select();
            document.execCommand("copy");
         }
      </script>
   </body>
</html>

When the script gets executed, it will generate an output consisting of text field along with two buttons one is generate and other is copy on the webpage. When the user clicks the generate button it will generate the password, when user clicks the copy the generated password will gets copied.

Updated on: 21-Apr-2023

472 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements