Verify if the updated array includes the unique symbol by utilizing a hashmap

Just starting out with JavaScript programming and looking for some help. I need to create a password generator that includes special characters and numbers.

const chars = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,"!", "@", "#", "$", "%" ]
const specialChars = ["!", "@", "#", "$", "%"]
const nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const genEl = document.getElementById("generate-el")
const inputEl = document.getElementById("input-el")
genEl.addEventListener("click", generate);
let pass = [];

let randSpecialChars = specialChars[Math.floor(Math.random() * specialChars.length)]
let randNums = nums[Math.floor(Math.random() * nums.length)]

const table ={};
table['randSpecialChars'] = randSpecialChars;
table['randNums'] = randNums;

function generate(){
    for(let i=0; i<10 && i<chars.length; i++){
        pass[i] = chars[Math.floor(Math.random() * chars.length)];
        inputEl.value = pass.join('');
};

    for(let i=0; i<pass.length; i++){
        if(specialChars.includes(pass[i])){
            return
        }
        else if(nums.includes(pass[i])){
            return
        }
        else{
            if(pass.includes(table['randSpecialChars'])=== false){
            pass.pop();
            pass.push(table['randSpecialChars'])}
            else if(pass.includes(table['randNums']==false)){
            pass.pop();
            pass.push(table['randSpecialChars'])
            }
            
        }
    }
};

My approach: If the generated password does not contain the special character, remove the last element from the array and replace it with a random special character. The same logic applies to inserting a random number from the array into the password.

I would appreciate any assistance or suggestions for improvement. Thank you!

Answer №1

Perhaps this regex pattern will suit your needs:

/[ `!@#$%^&*()_+-=[]{};':"\|,.<>/?~]/

function checkForSpecialChars(password) {
    return /[ `!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/.test(password);
}
<input type="text" oninput="checkForSpecialChars(this.value) ? console.log('yup') : console.log('nope')">

If you are dealing with a text that includes a regex and need to replace a character within it, why limit yourself to just the last character? Why not any character?

let specialCharacter = "."; // Use your own choice here, this is just a test

let context = document.getElementById("foo");

let value = foo.value;

let position = Math.random() * value.length;

foo.value = value.substring(0, position - 1) + specialCharacter + value.substring(position);
<input type="text" value="123456789" id="foo">

By combining these two approaches, you can effectively solve your issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to extract form data from a div tag based on its class name?

I'm working with some code that looks like this: var iconContainer = document.getElementById('iconContainer'); var icon = iconContainer.getElementsByClassName("item"); for (var i = 0; i < icon.length; i++) { icon[i].addEventListener ...

How can I execute a HTTP POST request in Node.js using MongoDB and Mongoose?

I have completed my schema setup and now I am looking for guidance on how to perform an HTTP POST request. I am currently utilizing MongoDB with the Mongoose framework. By implementing this, I aim to view the JSON data I have posted when accessing localhos ...

When only showing the title to the client, it results in an undefined value

I have created a schema in mongoosejs that looks like this: var uploadSchema = mongoose.Schema({ title : String, happy : String, }); I am trying to show the data from my database on the client side (using ejs for templating) ...

Updating a property of a JavaScript class using a callback function inside the class method after an AJAX request

Here is the code snippet from my JavaScript file: var myApp = myApp || {}; myApp.TestClass = function () { this.testProperty = null; } myApp.TestClass.prototype = { constructor: this, testMethod: function () { var testClass = this; ...

The Tinymce toolbar buttons are missing text labels, leading to an accessibility issue in the audit

When using Tinymce, the toolbar buttons only display icons without any text. This has been causing issues with accessibility audit tools such as WAVE. Does anyone know how to add hidden text to these buttons? Thank you ...

Issue with JavaScript Onclick Event Handler

Rephrasing Full JavaScript Code. Javascript <div id="PopUp1" style="display: none; color: #FFFFFF;"></div> <div id="Mask"></div> <script type="text/javascript"> var Content = '<p>Content!!!!!</p><input ty ...

I am looking to send an ajax request from the themes directory's loyalty.tpl file to the LoyaltyModule.php file in PrestaShop version 1.6.1.5

How can I successfully send an ajax request from the theme file folder/loyalty.tpl to /public_html/test/modules/loyalty/LoyaltyModule.php in Prestashop 1.6.1.5? <input id="Gcash_id" name="Gcash_id" type="text" class="form-control grey" placeholder="Ent ...

Premature adjustment of images to window size changes

How can I make the images inside a divider move down when the right-end of the browser reaches them? Currently, they start moving down before the edge of the window is reached. Any suggestions on how to fix this? JSFIDDLE: https://jsfiddle.net/prtdaay1/2/ ...

Comparing "this" and $scope within the context of Angular

I have gone through similar questions and their answers, but I am still struggling to understand this. Any assistance on this would be greatly appreciated. The code snippet below functions correctly. However, if I substitute $scope with this before the bi ...

Display images next to each other with no need for a scroll bar

I'm currently developing a Roulette website and I am struggling to make the roulette animation function properly. I have an image for the roulette wheel, but I need the image to vanish after reaching a certain point and then loop around to the left. ...

Using jQuery to initiate a page load into a new page within the WorkLight platform

I need help redirecting to a new page when the current page is loaded. My website is built using jQuery mobile in combination with WorkLight. Index.html: <body> <div data-role="importpages" id="pageport"> </div> </body> ...

Creating JavaScript code using PHP

In my current project, there is a significant amount of JavaScript involved. I'm finding that simply generating basic strings and enclosing them within "<script>" tags may not be the most efficient approach. What are some alternative methods fo ...

Tips for setting up Angular $resourceProvider to use the GET method

I am currently utilizing $resource within AngularJS. I am looking to set up $resource using $resourceProvider in a way that allows me to manage the server response. For instance When making a get request for a user profile, I want to handle specific erro ...

Exploring the Differences Between NPM Jquery on the Client Side and Server

I'm still getting the hang of node and npm, so this question is more theoretical in nature. Recently, I decided to incorporate jQuery into my website by running npm install jquery, which placed a node_modules directory in my webpage's root along ...

Countdown Timer in React Native

Hey, I am new to React Native and JavaScript. I want to create a simple countdown where you can input a number and select the type of countdown - whether it's in seconds, minutes, or hours. For example, if I choose 'seconds' in a dropdown an ...

Receive an HTTP POST request within JavaScript without using Ajax in Symfony 4.1

Searching for a way to handle an event triggered by a PHP post, not through Ajax. I would like to show a spinner when the form is posted using PHP. In JavaScript, it's easy with code like this: $(document).on({ ajaxStart: function() { $('#p ...

What is the origin of the term "res" in a NodeJS http request handler function?

In many NodeJS applications, the following code pattern is commonly used: const express = require("express"); const app = express(); app.post("/some-route", (req, res) => { const data = req.body; } I am puzzled by the ...

Is it optimal to count negative indexes in JavaScript arrays towards the total array length?

When working in JavaScript, I typically define an array like this: var arr = [1,2,3]; It's also possible to do something like: arr[-1] = 4; However, if I were to then set arr to undefined using: arr = undefined; I lose reference to the value at ...

Using JavaScript variables to implement real-time functionality through AJAX

I'm using PHP to fetch values from a database and need to display them in real-time as they change every second. Here is my PHP code: $sql = 'select * from cpu_usage where id=(select max(id) from cpu_usage)'; $login ='select count(*) ...

What is the best way to assign classes to dynamically generated elements within a loop?

I have used a loop to create multiple components <li v-for="card in cardID" :key="card"> <app-profile class="profile" :id="cardID[i++]"></app-profile> </li> My goal is to wrap all these c ...