JavaScript Password Generator In Console For Tutorial

Last Edited: 2023-04-30 19:53:17

My original idea was to drop the JavaScript code that I spoke of in the video below in the description of the YouTube video, however, I did not know that angle brackets, which I've known as less-than and greater-than signs are not allowed in the description at YouTube.  I put this blog post up to show the code.  I also decided to put together a less compacted version since you are probably trying to learn JavaScript.  Both sets of code do the same thing, with this you can see that even vast differences in code style can get you the same result.

let a=[];[...crypto.randomUUID().replace(/[^0-9a-z]/g, '')].forEach(c=>a.push(((Math.random()*10)<5?(isNaN(parseInt(c))?c.toUpperCase():'!@#$%^&*'.split('')[Math.floor(Math.random()*10)]):c)));console.log(a.join(''));

While making the video, I learned that the above code will not work if the tab is connected to an insecure site.  For instance, I have a local server running at home and did not bother getting an SSL signed for it so the browser reads "Not Secure" where there's normally a lock.

I did learn that this code will run in the console normally accessible by right clicking on the page and choosing Inspect, then the Console tab, on any blank tab.  Or any tab that you open without putting in a web address.

// start with an empty array
let a = [];
// define symbols to possibly use
let symbols = '!@#$%^&*';
// go get a UUID from JavaScript
// this function will fail if connected to unsecure website
let uuid = crypto.randomUUID();
// remove the hyphens
uuid = uuid.replace(/[^0-9a-z]/g, '');
// explode into an array with one character per element
uuid = uuid.split('');
// loop through each character and do something to each element with a character
uuid.forEach(c => {
// pseudorandom for half-ish the time
if (Math.random()*10 < 5) {
// if it's NOT a number, change it to uppercase
if (isNaN(parseInt(c))) {
c = c.toUpperCase();
} else {
// otherwise, replace it for a random symbol
// get a pseudorandom number between 0 and one less than how many symbols
let r = Math.random()*(symbols.length-1);
// get rid of any decimal places
r = Math.floor(r);
c = symbols[r];
} else {
// make no changes to our character
// normally this else would not be here
// push() the character c into the array a
// join the array back together
a = a.join('');
// output the password to the console

This code does the same thing, takes up a lot more space, but has comments to help you understand what each line of code is trying to do.  This can either run in an HTML file within <script> tags, or you can cut and paste this sucker into the console and hit enter.  This will work as long as the page you are on hasn't used the variable "a"; it will error out if it has.  If that happens, try just a tab with no webpage loaded in it.

I also put the above code in a page here too



Recent Posts