Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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. In this article, we'll learn how to create a password generator using JavaScript and the Math.random() method.
Let's dive into creating a password generator step by step. We'll use Math.random() to generate cryptographically secure random passwords with customizable length and character sets.
Understanding Math.random()
The JavaScript Math.random() function returns a floating-point pseudo-random number between 0 (inclusive) and 1 (exclusive). We can scale this random number to select characters from our password character set.
Syntax
Math.random()
Method 1: Simple Fixed-Length Password Generator
In this example, we create a basic password generator that produces a 4-character password using a predefined character set:
<!DOCTYPE HTML>
<html>
<body style="text-align:center;background-color:#EAFAF1;">
<h3>Click to Generate Random Passwords</h3>
<button onclick="changepassword()">Generate Password</button>
<br><br>
<div>
<p id="tutorial"></p>
</div>
<script>
var element_down = document.getElementById("tutorial");
function passwordgenerator() {
var pass = '';
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@#$%^&*';
for (let i = 1; i <= 4; i++) {
var char = Math.floor(Math.random() * str.length);
pass += str.charAt(char);
}
return pass;
}
function changepassword() {
element_down.innerHTML = "Generated Password: " + passwordgenerator();
}
</script>
</body>
</html>
When you click the button, it generates a 4-character random password using uppercase letters, lowercase letters, numbers, and special characters.
Method 2: User-Defined Length Password Generator
This example allows users to specify the password length by entering a number:
<!DOCTYPE HTML>
<html>
<body style="text-align:center;background-color:#E8DAEF;">
<h3>Custom Length Password Generator</h3>
<input type="text" id="digitspassword" oninput="generatepassword()" placeholder="Enter length (1-20)"/>
<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 (UserInput !== '' && UserInput > 0 && UserInput <= 20) {
for (var i = 0; i < UserInput; i++) {
text += shuffle.charAt(Math.floor(Math.random() * shuffle.length));
}
Results.innerHTML = "Password: " + text;
} else if (UserInput > 20) {
Results.innerHTML = "Maximum length is 20 characters";
} else {
Results.innerHTML = "";
}
}
</script>
</body>
</html>
Enter a number in the input field to generate a password of that specific length. The password updates automatically as you type.
Method 3: Advanced Password Generator with Copy Function
This example provides a complete password generator with generate and copy functionality:
<!DOCTYPE HTML>
<html>
<head>
<style>
.container {
text-align: center;
margin: 20px;
}
.button {
font-size: 16px;
margin: 10px;
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
.button:hover {
background-color: #45a049;
}
#passwordField {
padding: 10px;
font-size: 16px;
width: 300px;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<h2>Advanced Password Generator</h2>
<input type="text" id="passwordField" placeholder="Generated password will appear here" readonly>
<br>
<button class="button" onclick="generatePassword()">Generate Password</button>
<button class="button" onclick="copyPassword()">Copy Password</button>
</div>
<script>
function generatePassword() {
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]{}|;:,.<>?";
var passwordLength = 12;
var password = "";
for (var i = 0; i < passwordLength; i++) {
var randomIndex = Math.floor(Math.random() * chars.length);
password += chars.charAt(randomIndex);
}
document.getElementById("passwordField").value = password;
}
function copyPassword() {
var copyText = document.getElementById("passwordField");
if (copyText.value === "") {
alert("Generate a password first!");
return;
}
copyText.select();
copyText.setSelectionRange(0, 99999); // For mobile devices
try {
document.execCommand("copy");
alert("Password copied to clipboard!");
} catch (err) {
alert("Failed to copy password");
}
}
</script>
</body>
</html>
This generator creates a 12-character password with uppercase letters, lowercase letters, numbers, and special characters. Click "Generate Password" to create a new password, then "Copy Password" to copy it to your clipboard.
Key Features Explained
- Character Set: Mix of uppercase, lowercase, numbers, and special characters for strong passwords
-
Random Selection:
Math.floor(Math.random() * chars.length)selects random indices - Loop Generation: For loops build passwords character by character
- Input Validation: Ensures user input is within acceptable ranges
-
Copy Functionality: Uses
document.execCommand("copy")for clipboard access
Best Practices
When creating password generators, consider these security recommendations:
- Use a diverse character set including special symbols
- Generate passwords of at least 8-12 characters
- Validate user input to prevent errors
- Consider using cryptographically secure random number generators for production applications
Conclusion
JavaScript's Math.random() method provides an effective way to create password generators. By combining random character selection with user-friendly interfaces, you can build powerful tools for generating secure passwords with customizable length and complexity.
