Reputation: 33
How to count the amount of a specific set of characters (in an array) with JS (javascript)?
The answer to the question can be found below in the comments! You don't need to read the context explained in my question.
My specific context:
I got the idea to create a random password generator.
I succeeded in this.
I have 4 arrays with numbers (1-9), uppercase (A-Z), lowercase (a-z) and special characters (!,@,#,$,%,^,&,*,<,>,?).
Multiple functions create the sting: randomPassword. They have a var that counts how many characters of that category are inside the password.
I've now made a feature so the user can specify the number of letters, numbers and special characters the user wants in the password.
When the user requests a password longer than those amounts combined, the rest of the password gets filled up with random characters. However, the amount of characters in each category doesn't match up anymore, because a different function is used. I still want to display how many of each category are in the password. How could I make that work?
Thanks a lot!
I have removed the code block that I originally shared because it is too context-specific and not necessary to answer the general question.
Upvotes: 3
Views: 336
Reputation: 3660
Your code was really big I was not able to check... see if this is what you need:
I am using regular expressions (this is a cool thing you can learn later)
function countLowerCaseLetters(input) {
return input.length - input.replace(/[a-z]/g, '').length;
}
function countUpperCaseLetters(input) {
return input.length - input.replace(/[A-Z]/g, '').length;
}
function countNumbers(input) {
return input.length - input.replace(/[0-9]/g, '').length;
}
function countSpecialChars(input) {
return input.length - input.replace(/[!@#$%^&*<>?]/g, '').length;
}
Upvotes: 2