Related
I have a little problem here. I am solving some random questions from my book. Here is the task:
Task
A balanced string is one in which every character in the string appears an equal number of times as every other character. For example, "ab", "aaabbb" and "ababaabb" are balanced, but "abb" and "abbbaa" are not.
Additionally, strings may also include a wildcard character, "*". This wildcard character can represent any other character you wish. Furthermore, wildcards must represent another character; they cannot be left unused. A wild balanced string is a string in which all wildcards can be transformed into characters in such a way to produce a simple balanced string.
This challenge involves writing a function balanced(s) to check whether s is balanced.
Input is restricted to strings containing upper and lowercase alphabetical characters and the "*" wildcard character. The input string will match the regular expression
^[A-Za-z*]$*
Other Examples:
balanced("a") ⟹ true
balanced("ab") ⟹ true
balanced("abc") ⟹ true
balanced("abcb") ⟹ false
balanced("Aaa") ⟹ false
balanced("***********") ⟹ true
I have been able to get some answers but my algorithm is really failing me. I am thinking if there is anything I can do to adjust this code:
function balanced(s) {
const cMap = {};
for (let c of s) {
cMap[c] ? cMap[c]++ : (cMap[c] = 1);
}
const freq = new Set(Object.values(cMap));
if(s.includes('*')){
return true;
}
if (freq.size === 0 || freq.size === 1){
return true;
}
if (freq.size === 1) {
const max = Math.max(...freq);
const min = Math.min(...freq);
}
return false;
}
Proceeding mathematically
Another way to think about this is to simply do some arithmetic. To be balanced, each unique character after replacing the asterisks must occur the same number of times. So that number of times (counts) multiplied by the number of unique characters (letters) must equal the length of the input string (including the asterisks.) This count must be at least as large as the largest count of an individual character. And the number of letters in the output must be at least as large as the number of unique letters in the input. The only other restriction is that since the letters are taken from the lower- and upper-case letters, there can be no more than 52 of them.
In other words:
A string (of length `n`) is balanceable if
there exist positive integers `count` and `letters`
such that
`count` * `letters` = `n` and
`letters` <= 52 and
`letters` >= number of unique letters in the input (ignoring asterisks) and
`count` >= max of the counts of each individual (non-asterisk) letter in the input
With a helper function to find all the factor-pairs for a number, we can then write this logic directly:
// double counts [x, x] for x^2 -- not an issue for this problem
const factorPairs = (n) =>
[...Array (Math .floor (Math .sqrt (n)))] .map ((_, i) => i + 1)
.flatMap (f => n % f == 0 ? [[f, n / f], [n / f, f]] : [])
const balanced = ([...ss]) => {
const chars = [...new Set (ss .filter (s => s != '*'))]
const counts = ss .reduce (
(counts, s) => s == '*' ? counts : ((counts [s] += 1), counts),
Object .fromEntries (chars .map (l => [l, 0]))
)
const maxCount = Math.max (... Object.values (counts))
return factorPairs (ss .length) .some (
([count, letters]) =>
letters <= 52 &&
letters >= chars .length &&
count >= maxCount
)
}
const tests = [
'a', 'ab', 'abc', 'abcb', 'Aaa', '***********',
'****rfdd****', 'aaa**bbbb*', 'aaa**bbbb******',
'C****F***R***US***R**D***YS*****H***', 'C****F***R***US***R**D***YS*****H**',
'KSFVBX'
]
tests .forEach (s => console .log (`balanced("${s}") //=> ${balanced(s)}`))
.as-console-wrapper {max-height: 100% !important; top: 0}
factorPairs simply finds all the factoring of a number into ordered pairs of number. for instance, factorPairs (36) yields [[1, 36], [36, 1], [2, 18], [18, 2], [3, 12], [12, 3], [4, 9], [9, 4], [6, 6], [6, 6]]. Because we are only checking for the existence of one, we don't need to improve this function to return the values in a more logical order or to only return [6, 6] once (whenever the input is a perfect square.)
We test each result of the above (as [count, letters]) until we find one that matches and return true, or we make it through the list without finding one and return false.
Examples
So in testing this: 'C****F***R***US***R**D***YS*****H***', we have a string of length 36. We end up with these 8 unique characters: ['C', 'F', 'R', 'U', 'S', 'D', 'Y', 'H'], and these counts: {C: 1, F: 1, R: 2, U: 1, S: 2, D: 1, Y: 1, H: 1}, and our maxCount is 2
We then test the various factor-pairs generated for 36
count: 1, letters: 36 (fails because count is less than 2)
count: 36, letters: 1 (fails because letters is less than 8)
count: 2, letters: 18 (succeeds, and we return true)
And we don't need to test the remaining factor-pairs.
An example of using 18 letters, twice each could be:
C****F***R***US***R**D***YS*****H***
CCaabFFbcRcdUUSdeeRffDDgYYSghhiiHHjj - balanced
Note that this is not necessarily the only pair that will work. For instance, if we'd made it to count: 4, letters: 9, we could also make it work:
C****F***R***US***R**D***YS*****H***
CCCCFFFFRRRUUUSUDDRDYDSYYYSSxxxxHHHH - balanced
But the question is whether there was any such solution, so we stop when finding the first one.
If, on the other hand, we had one fewer asterisk in the input, we would test this: 'C****F***R***US***R**D***YS*****H**', with a length of 35. We end up with the same 8 unique characters: ['C', 'F', 'R', 'U', 'S', 'D', 'Y', 'H'], and these same counts: {C: 1, F: 1, R: 2, U: 1, S: 2, D: 1, Y: 1, H: 1}, and our maxCount is still 2.
We then test the various factor-pairs generated for 35
count: 1, letters: 35 (fails because count is less than 2)
count: 35, letters: 1 (fails because letters is less than 8)
count: 5, letters: 7 (fails because letters is less than 8)
count: 7, letters: 5 (fails because letters is less than 8)
and we've run out of factor-pairs, so we return false.
An alternate formulation
There's nothing particularly interesting in the code itself. It does the obvious thing at each step. (Although do note the destructuring of the input string to balanced, turning the String into an array of characters.) But it does something I generally prefer not to do, using assignment statements and a return statement. I prefer to work with expressions instead of statements as much as possible. I also prefer to extract helper functions, even if they're only used once, if they help clarify the flow. So I'm might rewrite as shown here:
const range = (lo, hi) =>
[... Array (hi - lo + 1)] .map ((_, i) => i + lo)
// double counts [x, x] for x^2 -- not an issue for this problem
const factorPairs = (n) =>
range (1, Math .floor (Math .sqrt (n)))
.flatMap (f => n % f == 0 ? [[f, n / f], [n / f, f]] : [])
const getUniqueChars = ([...ss]) =>
[... new Set (ss .filter (s => s != '*'))]
const maxOccurrences = ([...ss], chars) =>
Math.max (... Object .values (ss .reduce (
(counts, s) => s == '*' ? counts : ((counts [s] += 1), counts),
Object .fromEntries (chars .map (l => [l, 0]))
)))
const balanced = (
str,
chars = getUniqueChars (str),
maxCount = maxOccurrences (str, chars)
) => factorPairs (str .length) .some (
([count, letters]) =>
letters <= 52 &&
letters >= chars .length &&
count >= maxCount
)
const tests = [
'a', 'ab', 'abc', 'abcb', 'Aaa', '***********',
'****rfdd****', 'aaa**bbbb*', 'aaa**bbbb******',
'C****F***R***US***R**D***YS*****H***', 'C****F***R***US***R**D***YS*****H**',
'KSFVBX'
]
tests .forEach (s => console .log (`balanced("${s}") //=> ${balanced(s)}`))
.as-console-wrapper {max-height: 100% !important; top: 0}
But that changes nothing logically. The algorithm is the same.
Here is an algorithm that accomplishes this task:
First of all, sort the string:
var sorted = s.split("").sort().join("");
Now that the string is sorted, group all similar characters into an array. This is fairly easy to do using regular expressions:
var matches = sorted.match(/([A-Za-z])(\1)+/g);
If there are no matches (i.e. the string is empty or only has asterisks) then it is balanceable:
if (!matches) return true;
Next, get the number of asterisk * characters in the string:
var asterisks = sorted.match(/\*+/) ? sorted.match(/\*+/)[0].length : 0;
Now, find the most repeated character in the string and get the number of its occurences (i.e. find the mode of the string):
var maxocc = Math.max(...matches.map(match => match.length));
Calculate the number of required asterisks. This is done by subtracting the length of each of the matches from maxocc...
var reqAsterisks = matches.map(match => maxocc - match.length)
...then summing up the results:
.reduce((acc, val) => acc + val);
Get the number of extra asterisks by the subtracting the number of required asterisks from the total number of asterisks:
var remAsterisks = asterisks - reqAsterisks;
The question that arises now is, what to do with the remaining asterisks? You can either 1. distribute them evenly among the groups, 2. use them to create another group, or 3. do both at the same time. Note that you can do either or both of 1 and 2 multiple times. To do this, first define a variable that will hold the group length:
var groupLength = maxocc;
Then, repeatedly give each group one asterisk from the remaining asterisks. After that, check whether you can do 1 or 2 (described above) to get rid of the remaining asterisks. Everytime you do this, decrement remAsterisks by the number of asterisks you use and increment groupLength by one. This is accomplished by the following loop:
while(remAsterisks >= 0) {
if(remAsterisks == 0 || !(remAsterisks % matches.length) || remAsterisks == groupLength) {
return true;
} else {
remAsterisks -= matches.length;
groupLength++;
}
}
Here is the complete code
function balanced(s) {
var sorted = s.split("").sort().join("");
var matches = sorted.match(/([A-Za-z])(\1)*/g);
if (!matches) return true;
var asterisks = sorted.match(/\*+/) ? sorted.match(/\*+/)[0].length : 0;
var maxocc = Math.max(...matches.map(match => match.length));
var reqAsterisks = matches.map(match => maxocc - match.length).reduce((acc, val) => acc + val);
var remAsterisks = asterisks - reqAsterisks;
var groupLength = maxocc;
while(remAsterisks >= 0) {
if(remAsterisks == 0 || !(remAsterisks % matches.length) || remAsterisks == groupLength) {
return true;
} else {
remAsterisks -= matches.length;
groupLength++;
}
}
return false;
}
console.log(balanced("a"));
console.log(balanced("ab"));
console.log(balanced("abc"));
console.log(balanced("abcb"));
console.log(balanced("Aaa"));
console.log(balanced("***********"));
console.log(balanced("aaa**bbbb******));
You could count the characters and maintain a max count variable.
The return either the result of the length check of the keys with one or check every character without star by adjusting star count.
At the end check this property for falsyness to have either a zero count or just undefined.
function balanced(string) {
let max = 0,
stars = 0,
counts = [...string].reduce((r, c) => {
if (c === '*') {
stars++;
return r;
}
r[c] = (r[c] || 0) + 1;
if (max < r[c]) max = r[c];
return r;
}, {}),
keys = Object.keys(counts);
if (keys.length <= 1) return true;
return keys.every(c => {
if (counts[c] === max) return true;
if (stars >= max - counts[c]) {
stars -= max - counts[c];
return true;
}
}) && (!stars || stars % keys.length === 0);
}
console.log(balanced("a")); // true
console.log(balanced("ab")); // true
console.log(balanced("abc")); // true
console.log(balanced("***********")); // true
console.log(balanced("****rfdd****")); // true
console.log(balanced("aaa**bbbb*")); // true
console.log(balanced("abcb")); // false
console.log(balanced("Aaa")); // false
.as-console-wrapper { max-height: 100% !important; top: 0; }
This is a bit late as I was just wrapping this up as Nina posted. Posting for posterity.
Update
After editing this got a little longer than expected. The approach here is to first map the count of letters and number of wildcards. There are several checks going on but the main idea is to distribute wildcards and check the character count. There are 4 scenarios:
We evenly distribute all wildcards to each letter. (balanced)
We distribute enough wildcards such that the characterCount for each letter is equal to the remaining wildcards. (balanced)
There are simply not enough wildcards to distribute so that each letter can be balanced. (not balanced)
The remaining wildcards after distribution cannot be distributed to produce scenarios 1 or 2. (not balanced)
function balanced(s) {
const MAX = 52; // All lowercase and uppercase characters.
let wildcards = 0;
const map = {};
let characterCount = 0;
for (const char of s) {
if (char === '*') {
wildcards++;
} else {
if (!map[char]) {
map[char] = 0;
}
map[char]++;
if (map[char] > characterCount) {
characterCount = map[char];
}
}
}
const mapSize = Object.keys(map).length;
// Edge case: All characters are mapped and we see only 1 of each. This is balanced iff we can allocate wildcards uniformly.
if (mapSize === MAX && characterCount === 1) {
return wildcards % MAX === 0;
}
// Edge case: Not all characters are mapped and the number of wildcards is less than the count of remaining map slots.
if (mapSize < MAX && characterCount === 1 && wildcards <= (MAX - mapSize)) {
return true;
}
// Edge case: The string contains only wildcards. We can then assign all wildcards to 'a' and this will be balanced.
if (wildcards === s.length) {
return true;
}
for (const char in map) {
while (map[char] + 1 <= characterCount) {
map[char]++;
wildcards--;
}
// cannot distribute enough to balance out (scenario 3)
if (wildcards < 0) return false;
}
// If the remaining wildcards is a multiple (places) of the largest count, and the total count is less than MAX, this is balanced.
if (wildcards % characterCount === 0) {
const places = wildcards / characterCount;
if (mapSize + places <= MAX) {
return true;
}
}
/*
We can quickly check for scenario 2 by noting that it is equivalent to solving this equation for n
wildcards - n * mapSize === characterCount + n
*/
if (Number.isInteger((wildcards - characterCount) / (mapSize + 1))) {
return true;
}
// We distribute the most wildcards possible to each map entry.
wildcards -= parseInt(wildcards / mapSize);
// remaining wildcards cannot be distributed evenly (scenario 4)
if (wildcards && wildcards % mapSize !== 0) {
return false;
}
// remaining wildcards can be distributed evenly (scenario 1)
return true;
}
console.log(balanced("a")); // true
console.log(balanced("ab")); // true
console.log(balanced("ab*")); // true
console.log(balanced("abc")); // true
console.log(balanced("abcb")); // false
console.log(balanced("Aaa")); // false
console.log(balanced("***********")); // true
console.log(balanced("***KSFV***BX")); // true
console.log(balanced("C****F***R***US***R**D***YS*****H***")); // true
console.log(balanced("aaa**bbbb******")); // true
console.log(balanced("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ*")); // false
console.log(balanced("N****UWIQRXNW*QRE*")); // true
console.log(balanced("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ****************************************************")); // true
Here's my approach to solving this problem.
const isBalanced = string => {
const props = {};
let isBalanced = true;
const pattern = new RegExp(`^[A-Za-z\*]*$`);
if(pattern.test(string) && string.length <= 52){
const strArr = string.split("");
let previous = "";
while(strArr.length){
let current = strArr.shift();
if(current === "*"){
//transform all wildcards
if(previous.length > 0){
const propsArr = Object.keys(props);
let prevKey = "";
while(propsArr.length){
let key = propsArr.shift();
if(prevKey.length > 0){
//take the lowest value
let val = props[key] > props[prevKey] ? prevKey : key;
if(props[key] !== props[prevKey]){
//increment the value
props[val] = props[val] + 1;
break;
}else if(propsArr.length === 0){
strArr.push(val);
}
}
prevKey = key;
}//end while
}
}else{
if(!props[current]){
props[current] = 1;
}else{
props[current] = props[current] + 1;
}
previous = current;
}//end else
}//end while
}//end regex
if(Object.keys(props).length > 0 && props.constructor === Object){
const checkArr = Object.keys(props);
let previous = "";
while(checkArr.length){
let key = checkArr.shift();
if(previous.length > 0 && props[key] !== props[previous]){
isBalanced = false;
break;
}
previous = key;
}
}
return isBalanced;
}
console.log(isBalanced("a")); //true
console.log(isBalanced("ab")); //true
console.log(isBalanced("abc")); //true
console.log(isBalanced("abcb")); //false
console.log(isBalanced("Aaa")); //false
console.log(isBalanced("***********")); //true
console.log(isBalanced("aaa**bbbb******")); //flase
The aim is to arrange the strings into an object with the strings as the keys and the number of occurence as the value.
I want to create a javascript function to flip 1's to 0's in a natural number and I'm out of Ideas to achieve this,
Actually, I had a couple of URL's, and I replaced all 0's from a query parameter with 1's and now I no longer know the original parameter value, because there were few 1's in the original parameter value and now both are mixed, so basically I screwed myself,
The only solution for me is to try flipping each 1 to 0 and then 0's to 1's and test each number as the parameter.
This is the parameter value (after replacing 0's with 1's)
11422971
using above input I want to generate numbers as follows and test each of these
11422970
10422971
10422970
01422971
As you can see only 1's and 0's are changing, the change according to binary,
Each position in your string can be one of n characters:
A "0" can be either "0" or "1"
A "1" can be either "0" or "1"
Any other character c can only be c
We can store this in an array of arrays:
"11422971" -> [ ["0", "1"], ["0, "1"], ["4"], ... ]
To transform your string to this format, you can do a split and map:
const chars = "11422971"
.split("")
.map(c => c === "1" || c === "0" ? ["1", "0"] : [ c ]);
Once you got this format, the remaining logic is to create all possible combinations from this array. There are many ways to do so (search for "array combinations" or "permutations"). I've chosen to show a recursive pattern:
const chars = "11422971"
.split("")
.map(c =>
c === "1" || c === "0"
? ["1", "0"]
: [ c ]
);
const perms = ([ xs, ...others ], s = "", ps = []) =>
xs
? ps.concat(...xs.map(x => perms(others, s + x, ps)))
: ps.concat(s);
console.log(perms(chars));
you can do it with a number like a string, and after parse it, something like that
var number= "12551";
number= number.replace("1","0");
The result of number will be "02550"
after that parse number to int
This will generate all permutations.
const generatePermutations = (number) => {
let digits = number.split('');
// find out which digits can be flipped
let digitPositions = digits.reduce((acc, val, i) => {
if (val === '0' || val === '1') acc.push(i);
return acc;
}, []);
// we're going to be taking things in reverse order
digitPositions.reverse();
// how many digits can we flip
let noBits = digitPositions.length;
// number of permutations is 2^noBits i.e. 3 digits means 2^3 = 8 permutations.
let combinations = Math.pow(2, digitPositions.length);
let permutations = [];
// for each permutation
for (var p = 0; p < combinations; p++) {
// take a copy of digits for this permutation
permutations[p] = digits.slice();
// set each of the flippable bits according to the bit positions for this permutation
// i = 3 = 011 in binary
for (var i = 0; i < noBits; i++) {
permutations[p][digitPositions[i]] = '' + ((p >> i) & 1);
}
permutations[p] = permutations[p].join('');
}
return permutations;
};
console.log(generatePermutations('11422970'));
In case your looking for a recursive approach:
function recursive(acc, first, ...rest) {
if(!first) return acc;
if(first == '0' || first == '1') {
var acc0 = acc.map(x => x + '0');
var acc1 = acc.map(x => x + '1');
return recursive([].concat(acc0, acc1), ...rest);
} else {
return recursive(acc.map(x => x + first), ...rest);
}
}
recursive([''], ...'11422971')
// output ["00422970", "10422970", "01422970", "11422970", "00422971", "10422971", "01422971", "11422971"]
This just counts in binary and fills out a template for each value.
function getPossibleValues(str) {
function getResult(n) {
let nIndex = 0;
const strValue = n.toString(2).padStart(nDigits, '0');
return str.replace(rxMatch, () => strValue.charAt(nIndex++));
}
const rxMatch = /[01]/g;
const nDigits = str.length - str.replace(rxMatch, '').length;
const nMax = Math.pow(2, nDigits);
const arrResult = [];
for(let n = 0; n<nMax; n++) {
arrResult.push(getResult(n));
}
return arrResult;
}
console.log(getPossibleValues('11422970'));
Thank you all to respond, you saved my life, btw the approach I used was,
0- convert the number into a string. (so we can perform string operations like split())
1- count the number of 1's in the string (let's say the string is "11422971", so we get three 1's, I used split('1')-1 to count)
2- generate binary of three-digit length,(ie from 000 to 111). three came from step 1.
2- break down the string to single chars, (we'll get
array=['1','1','4','2','2','9','7','1'] )
3- take the first binary number (ie b=0b000)
4- replace first 1 from the character array with the first binary digit of b (ie replace 1 with 0), similarly replace second 1 with the second binary digit of b and so on.
5- we'll get the first combination (ie "00422970")
5- repeat step 3 and 4 for all binary numbers we generated in step 2.
I want to convert a number to its corresponding alphabet letter. For example:
1 = A
2 = B
3 = C
Can this be done in javascript without manually creating the array?
In php there is a range() function that creates the array automatically. Anything similar in javascript?
Yes, with Number#toString(36) and an adjustment.
var value = 10;
document.write((value + 9).toString(36).toUpperCase());
You can simply do this without arrays using String.fromCharCode(code) function as letters have consecutive codes. For example: String.fromCharCode(1+64) gives you 'A', String.fromCharCode(2+64) gives you 'B', and so on.
Snippet below turns the characters in the alphabet to work like numerical system
1 = A
2 = B
...
26 = Z
27 = AA
28 = AB
...
78 = BZ
79 = CA
80 = CB
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var result = ""
function printToLetter(number){
var charIndex = number % alphabet.length
var quotient = number/alphabet.length
if(charIndex-1 == -1){
charIndex = alphabet.length
quotient--;
}
result = alphabet.charAt(charIndex-1) + result;
if(quotient>=1){
printToLetter(parseInt(quotient));
}else{
console.log(result)
result = ""
}
}
I created this function to save characters when printing but had to scrap it since I don't want to handle improper words that may eventually form
Just increment letterIndex from 0 (A) to 25 (Z)
const letterIndex = 0
const letter = String.fromCharCode(letterIndex + 'A'.charCodeAt(0))
console.log(letter)
UPDATE (5/2/22): After I needed this code in a second project, I decided to enhance the below answer and turn it into a ready to use NPM library called alphanumeric-encoder. If you don't want to build your own solution to this problem, go check out the library!
I built the following solution as an enhancement to #esantos's answer.
The first function defines a valid lookup encoding dictionary. Here, I used all 26 letters of the English alphabet, but the following will work just as well: "ABCDEFG", "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "GFEDCBA". Using one of these dictionaries will result in converting your base 10 number into a base dictionary.length number with appropriately encoded digits. The only restriction is that each of the characters in the dictionary must be unique.
function getDictionary() {
return validateDictionary("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
function validateDictionary(dictionary) {
for (let i = 0; i < dictionary.length; i++) {
if(dictionary.indexOf(dictionary[i]) !== dictionary.lastIndexOf(dictionary[i])) {
console.log('Error: The dictionary in use has at least one repeating symbol:', dictionary[i])
return undefined
}
}
return dictionary
}
}
We can now use this dictionary to encode our base 10 number.
function numberToEncodedLetter(number) {
//Takes any number and converts it into a base (dictionary length) letter combo. 0 corresponds to an empty string.
//It converts any numerical entry into a positive integer.
if (isNaN(number)) {return undefined}
number = Math.abs(Math.floor(number))
const dictionary = getDictionary()
let index = number % dictionary.length
let quotient = number / dictionary.length
let result
if (number <= dictionary.length) {return numToLetter(number)} //Number is within single digit bounds of our encoding letter alphabet
if (quotient >= 1) {
//This number was bigger than our dictionary, recursively perform this function until we're done
if (index === 0) {quotient--} //Accounts for the edge case of the last letter in the dictionary string
result = numberToEncodedLetter(quotient)
}
if (index === 0) {index = dictionary.length} //Accounts for the edge case of the final letter; avoids getting an empty string
return result + numToLetter(index)
function numToLetter(number) {
//Takes a letter between 0 and max letter length and returns the corresponding letter
if (number > dictionary.length || number < 0) {return undefined}
if (number === 0) {
return ''
} else {
return dictionary.slice(number - 1, number)
}
}
}
An encoded set of letters is great, but it's kind of useless to computers if I can't convert it back to a base 10 number.
function encodedLetterToNumber(encoded) {
//Takes any number encoded with the provided encode dictionary
const dictionary = getDictionary()
let result = 0
let index = 0
for (let i = 1; i <= encoded.length; i++) {
index = dictionary.search(encoded.slice(i - 1, i)) + 1
if (index === 0) {return undefined} //Attempted to find a letter that wasn't encoded in the dictionary
result = result + index * Math.pow(dictionary.length, (encoded.length - i))
}
return result
}
Now to test it out:
console.log(numberToEncodedLetter(4)) //D
console.log(numberToEncodedLetter(52)) //AZ
console.log(encodedLetterToNumber("BZ")) //78
console.log(encodedLetterToNumber("AAC")) //705
UPDATE
You can also use this function to take that short name format you have and return it to an index-based format.
function shortNameToIndex(shortName) {
//Takes the short name (e.g. F6, AA47) and converts to base indecies ({6, 6}, {27, 47})
if (shortName.length < 2) {return undefined} //Must be at least one letter and one number
if (!isNaN(shortName.slice(0, 1))) {return undefined} //If first character isn't a letter, it's incorrectly formatted
let letterPart = ''
let numberPart= ''
let splitComplete = false
let index = 1
do {
const character = shortName.slice(index - 1, index)
if (!isNaN(character)) {splitComplete = true}
if (splitComplete && isNaN(character)) {
//More letters existed after the numbers. Invalid formatting.
return undefined
} else if (splitComplete && !isNaN(character)) {
//Number part
numberPart = numberPart.concat(character)
} else {
//Letter part
letterPart = letterPart.concat(character)
}
index++
} while (index <= shortName.length)
numberPart = parseInt(numberPart)
letterPart = encodedLetterToNumber(letterPart)
return {xIndex: numberPart, yIndex: letterPart}
}
this can help you
static readonly string[] Columns_Lettre = new[] { "A", "B", "C"};
public static string IndexToColumn(int index)
{
if (index <= 0)
throw new IndexOutOfRangeException("index must be a positive number");
if (index < 4)
return Columns_Lettre[index - 1];
else
return index.ToString();
}
How can I convert Persian/Arabic numbers to English numbers with a simple function?
arabicNumbers = ["١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩", "٠"]
persianNumbers = ["۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹", "۰"]
It is the same schema, but the code pages are different.
Oneliner of all 6 possible translations between English, Arabic, and persian Digits.
Caution!! Please note that this solution is not efficient and therefore is not recommended for production code. It is only good as a oneliner. In these methods the '۰۱۲۳۴۵۶۷۸۹' string is created every time for every digit! It is much wiser to create the string once and store it in a variable and use that variable instead. Also, most likely a simple for-loop is much faster!
const e2p = s => s.replace(/\d/g, d => '۰۱۲۳۴۵۶۷۸۹'[d])
const e2a = s => s.replace(/\d/g, d => '٠١٢٣٤٥٦٧٨٩'[d])
const p2e = s => s.replace(/[۰-۹]/g, d => '۰۱۲۳۴۵۶۷۸۹'.indexOf(d))
const a2e = s => s.replace(/[٠-٩]/g, d => '٠١٢٣٤٥٦٧٨٩'.indexOf(d))
const p2a = s => s.replace(/[۰-۹]/g, d => '٠١٢٣٤٥٦٧٨٩'['۰۱۲۳۴۵۶۷۸۹'.indexOf(d)])
const a2p = s => s.replace(/[٠-٩]/g, d => '۰۱۲۳۴۵۶۷۸۹'['٠١٢٣٤٥٦٧٨٩'.indexOf(d)])
e2p("asdf1234") // asdf۱۲۳۴
e2a("asdf1234") // asdf١٢٣٤
p2e("asdf۱۲۳۴") // asdf1234
a2e("asdf١٢٣٤") // asdf1234
p2a("asdf۱۲۳۴") // asdf١٢٣٤
a2p("asdf١٢٣٤") // asdf۱۲۳۴
Explaination:
(s => f(s))(x) is a lambda function that is immediately executed, and will be equal to f(x)
s.replace(pattern, function) looks for matches of pattern in s, for every match m it will replace m with function(m) in the string.
/\d/g is a regex pattern, \d means a digit in the English language, g means global. If you don't specify the g it will only match the first occurrence, otherwise it will match all the occurrences.
In this case for every English digit d in the string, that digit will be replaced by '۰۱۲۳۴۵۶۷۸۹'[d] so, 3 will be replaced by the third index in that list('۰۱۲۳۴۵۶۷۸۹') which is '۳'
/[۰-۹]/g is the equivalent regex for Persian digits this time we can't use the same method, before we took advantage of the fact that javascript is dynamically typed and that d is automatically converted from a string(regex match) to a number(array index) (you can do '1234'['1'] in javascript which is the same as '1234'[1])
but this time we can't do that because '1234'['۱'] is invalid. so we use a trick here and use indexOf which is a function that tells us the index of an element in an array(here a character in a string) so, '۰۱۲۳۴۵۶۷۸۹'.indexOf(۳) will give us 3 because '۳' is the third index in the string '۰۱۲۳۴۵۶۷۸۹'
Use this simple function to convert your string
var
persianNumbers = [/۰/g, /۱/g, /۲/g, /۳/g, /۴/g, /۵/g, /۶/g, /۷/g, /۸/g, /۹/g],
arabicNumbers = [/٠/g, /١/g, /٢/g, /٣/g, /٤/g, /٥/g, /٦/g, /٧/g, /٨/g, /٩/g],
fixNumbers = function (str)
{
if(typeof str === 'string')
{
for(var i=0; i<10; i++)
{
str = str.replace(persianNumbers[i], i).replace(arabicNumbers[i], i);
}
}
return str;
};
Be careful, in this code the persian numbers codepage are different with the arabian numbers.
Example
var mystr = 'Sample text ۱۱۱۵۱ and ٢٨٢٢';
mystr = fixNumbers(mystr);
Refrence
this is a simple way to do that:
function toEnglishDigits(str) {
// convert persian digits [۰۱۲۳۴۵۶۷۸۹]
var e = '۰'.charCodeAt(0);
str = str.replace(/[۰-۹]/g, function(t) {
return t.charCodeAt(0) - e;
});
// convert arabic indic digits [٠١٢٣٤٥٦٧٨٩]
e = '٠'.charCodeAt(0);
str = str.replace(/[٠-٩]/g, function(t) {
return t.charCodeAt(0) - e;
});
return str;
}
an example:
console.log(toEnglishDigits("abc[0123456789][٠١٢٣٤٥٦٧٨٩][۰۱۲۳۴۵۶۷۸۹]"));
// expected result => abc[0123456789][0123456789][0123456789]
best way to do that return index of number in array:
String.prototype.toEnglishDigits = function () {
return this.replace(/[۰-۹]/g, function (chr) {
var persian = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
return persian.indexOf(chr);
});
};
The most High Performance (Fast & Accurate) function that can support both Persian/Arabic digits (Unicode numeral characters) is this:
function toEnDigit(s) {
return s.replace(/[\u0660-\u0669\u06f0-\u06f9]/g, // Detect all Persian/Arabic Digit in range of their Unicode with a global RegEx character set
function(a) { return a.charCodeAt(0) & 0xf } // Remove the Unicode base(2) range that not match
)
}
sample='English: 0123456789 - Persian: ۰۱۲۳۴۵۶۷۸۹ - Arabic: ٠١٢٣٤٥٦٧٨٩';
// English: 0123456789 - Persian: 0123456789 - Arabic: 0123456789
console.log( toEnDigit(sample) );
How it work
First by using replace() + RegEx Character Set in range of Arabic Digit Unicode U+0660 - U+0669 = ٠ ... ۹ & Persian Digit Unicode U+06F0 - U+06F9 = ۰ ... ۹ it will detect any character of the string that match it.
Then because Basic Latin Digits (ASCII) have same ends in Unicode U+0030 - U+0039=0-9, So if we remove the difference of them in base, the end can be same.
For that we can use Bitwise AND (&) operation between their Char-code by using charCodeAt() to just the same part stay.
Explain:
// x86 (Base 10) --> Binary (Base 2)
'٤'.charCodeAt(0); // 1636 (Base 10)
'۴'.charCodeAt(0); // 1780 (Base 10)
(1636).toString(2); // 0000000000000000000001100110 0100 (Base 2)
(1780).toString(2); // 0000000000000000000001101111 0100 (Base 2)
(4).toString(2); // 0000000000000000000000000000 0100 (Base 2)
// We need a // 0000000000000000000000000000 1111 (Base 2)
// To And it, for keeping just the 1's
// 0xf = 15
(15).toString(2); // 0000000000000000000000000000 1111 (Base 2)
// So
(
1780 // 0000000000000000000001101111 0100 (Base 2)
& // AND (Operation)
15 // 0000000000000000000000000000 1111 (Base 2)
)
==
4 // 0000000000000000000000000000 0100 (Base 2)
// ---> true
// Also (1636 & 15) == 4 <--- true
Minified version (All Browsers):
function toEnDigit(s){return s.replace(/[\u0660-\u0669\u06f0-\u06f9]/g,function(a){return a.charCodeAt(0)&15})}
OneLiner (Modern Browsers)
const toEnDigit=s=>s.replace(/[٠-٩۰-۹]/g,a=>a.charCodeAt(0)&15);
If the string may contain both "Arabic" and "Persian" numbers then a one-line "replace" can do the job as follows.
The Arabic and Persian numbers are converted to English equivalents. Other text remains unchanged.
Num= "۳٣۶٦۵any٥۵٤۶32٠۰"; // Output should be "33665any55453200"
Num = Num.replace(/[٠-٩]/g, d => "٠١٢٣٤٥٦٧٨٩".indexOf(d)).replace(/[۰-۹]/g, d => "۰۱۲۳۴۵۶۷۸۹".indexOf(d));
console.log(Num);
Short and easy!
"۰۱۲۳۴۵۶۷۸۹".replace(/([۰-۹])/g, function(token) { return String.fromCharCode(token.charCodeAt(0) - 1728); });
Or in a more modern manner
"۰۱۲۳۴۵۶۷۸۹".replace(/([۰-۹])/g, token => String.fromCharCode(token.charCodeAt(0) - 1728));
You could do something like this that uses the index of the number within the string to do the conversion:
// Returns -1 if `fromNum` is not a numeric character
function convertNumber(fromNum) {
var persianNums = '۰١۲۳۴۵۶۷۸۹';
return persianNums.indexOf(fromNum);
}
var testNum = '۴';
alert("number is: " + convertNumber(testNum));
Or map using a object like this:
// Returns -1 if `fromNum` is not a numeric character
function convertNumber(fromNum) {
var result;
var arabicMap = {
'٩': 9,
'٨': 8,
'٧': 7,
'٦': 6,
'٥': 5,
'٤': 4,
'٣': 3,
'٢': 2,
'١': 1,
'٠': 0
};
result = arabicMap[fromNum];
if (result === undefined) {
result = -1;
}
return result;
}
var testNum = '٤';
alert("number is: " + convertNumber(testNum));
Transforms any Persian or Arabic (or mixed) number to "English" numbers (Hindu–Arabic numerals)
var transformNumbers = (function(){
var numerals = {
persian : ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"],
arabic : ["٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩"]
};
function fromEnglish(str, lang){
var i, len = str.length, result = "";
for( i = 0; i < len; i++ )
result += numerals[lang][str[i]];
return result;
}
return {
toNormal : function(str){
var num, i, len = str.length, result = "";
for( i = 0; i < len; i++ ){
num = numerals["persian"].indexOf(str[i]);
num = num != -1 ? num : numerals["arabic"].indexOf(str[i]);
if( num == -1 ) num = str[i];
result += num;
}
return result;
},
toPersian : function(str, lang){
return fromEnglish(str, "persian");
},
toArabic : function(str){
return fromEnglish(str, "arabic");
}
}
})();
//////// ON INPUT EVENT //////////////
document.querySelectorAll('input')[0].addEventListener('input', onInput_Normal);
document.querySelectorAll('input')[1].addEventListener('input', onInput_Arabic);
function onInput_Arabic(){
var _n = transformNumbers.toArabic(this.value);
console.clear();
console.log( _n )
}
function onInput_Normal(){
var _n = transformNumbers.toNormal(this.value);
console.clear();
console.log( _n )
}
input{ width:90%; margin-bottom:1em; font-size:1.5em; padding:5px; }
<input placeholder="write in Arabic numerals">
<input placeholder="write in normal numerals">
function toEnglishDigits(str) {
const persianNumbers = ["۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹", "۰"]
const arabicNumbers = ["١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩", "٠"]
const englishNumbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
return str.split("").map(c => englishNumbers[persianNumbers.indexOf(c)] ||
englishNumbers[arabicNumbers.indexOf(c)] || c).join("")
}
toEnglishDigits("۶٦۵any٥32") // "665any532"
You can use the new Persian-tools library which is an awesome javascript library to deal with Persian words and numbers. Here is a sample for the task you asked for it:
import { digitsArToFa, digitsArToEn, digitsEnToFa, digitsFaToEn } from "persian-tools2";
digitsArToFa("٠١٢٣٤٥٦٧٨٩"); // "۰۱۲۳۴۵۶۷۸۹"
digitsArToEn("٠١٢٣٤٥٦٧٨٩"); // "0123456789"
digitsEnToFa("123۴۵۶"); // "۱۲۳۴۵۶"
digitsFaToEn("۰۱۲۳۴۵۶۷۸۹"); // "0123456789"
You can also find many other useful functionalities on the repository page of the library.
Based on MMMahdy-PAPION method, a short one-line to convert both Persian and Arabic numbers to English numbers and keep all other characters unchanged is the following:
const toEnDigit=n=>n.replace(/[٠-٩۰-۹]/g,n=>15&n.charCodeAt(0));
const toEnDigit=n=>n.replace(/[٠-٩۰-۹]/g,n=>15&n.charCodeAt(0));
sample='English: 0123456789 - Persian (فارسی): ۰۱۲۳۴۵۶۷۸۹ - Arabic (عربي): ٠١٢٣٤٥٦٧٨٩';
// English: 0123456789 - Persian: 0123456789 - Arabic: 0123456789
console.log(toEnDigit(sample) );
For React solution using typescript this might be useful:
// https://gist.github.com/alieslamifard/364862613408a98139da3cab40abbeb9
import React, { InputHTMLAttributes, useEffect, useRef } from 'react';
// Persian/Arabic To English Digit
const f2e = (event) => {
event.target.value = event.target.value
.replace(/[٠-٩]/g, (d) => '٠١٢٣٤٥٦٧٨٩'.indexOf(d))
.replace(/[۰-۹]/g, (d) => '۰۱۲۳۴۵۶۷۸۹'.indexOf(d));
return event;
};
const useForwardedRef = (ref) => {
const innerRef = useRef(null);
useEffect(() => {
if (!ref) return;
if (typeof ref === 'function') {
ref(innerRef.current);
} else {
ref.current = innerRef.current;
}
}, [ref]);
return innerRef;
};
const Input = React.forwardRef<HTMLInputElement, InputHTMLAttributes<HTMLInputElement>>(
(props, ref) => {
const innerRef = useForwardedRef(ref);
useEffect(() => {
innerRef.current?.addEventListener('keyup', f2e);
return () => {
innerRef.current?.removeEventListener('keyup', f2e);
};
}, [innerRef]);
return <input {...props} ref={innerRef} />;
},
);
export default Input;
Simply use Input instead of native input in your form :)
const convertToPersianDigits = (number) => number.toLocaleString('fa-IR')
convertToPersianDigits(100000) //۱۰۰٬۰۰۰
If you have your number string (a string representing a number) at hand, here is a function called paserNumber that converts that into an actual JS Number object:
function parseNumber(numberText: string) {
return Number(
// Convert Persian (and Arabic) digits to Latin digits
normalizeDigits(numberText)
// Convert Persian/Arabic decimal separator to English decimal separator (dot)
.replace(/٫/g, ".")
// Remove other characters such as thousands separators
.replace(/[^\d.]/g, "")
);
}
const persianDigitsRegex = [/۰/g, /۱/g, /۲/g, /۳/g, /۴/g, /۵/g, /۶/g, /۷/g, /۸/g, /۹/g];
const arabicDigitsRegex = [/٠/g, /١/g, /٢/g, /٣/g, /٤/g, /٥/g, /٦/g, /٧/g, /٨/g, /٩/g];
function normalizeDigits(text: string) {
for (let i = 0; i < 10; i++) {
text = text
.replace(persianDigitsRegex[i], i.toString())
.replace(arabicDigitsRegex[i], i.toString());
}
return text;
}
Note that the parse function is quite forgiving and the number string can be a combination of Persian/Arabic/Latin numerals and separators.
After getting a Number you can format it however you want with Number.toLocaleString function:
let numberString = "۱۲۳۴.5678";
let number = parseNumber(numberString);
val formatted1 = number.toLocaleString("fa"); // OR "fa-IR" for IRAN
val formatted2 = number.toLocaleString("en"); // OR "en-US" for USA
val formatted3 = number.toLocaleString("ar-EG"); // OR "ar" which uses western numerals
For more information about formatting numbers, refer to this answer.
What would be the best approach to creating a 8 character random password containing a-z, A-Z and 0-9?
Absolutely no security issues, this is merely for prototyping, I just want data that looks realistic.
I was thinking a for (0 to 7) Math.random to produce ASCII codes and convert them to characters. Do you have any other suggestions?
I would probably use something like this:
function generatePassword() {
var length = 8,
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
return retVal;
}
That can then be extended to have the length and charset passed by a parameter.
Real Quick-n-dirty™
Math.random().toString(36).slice(2, 10)
Voilà! 8 random alphanumeric characters.
The idea is to cast a random number (in the range 0..1) to a base36 string (lowercase a-z plus 0-9), and then fetch the first 8 characters after the leading zero and decimal point.
However, please be aware that different browsers and javascript implementations used to give different bit depth results for Math.random(). If you are running in an old pre-2016 chrome or pre-2017 safari browser, this might mean (in worst case scenario) you get a shorter password than 8 characters. Though, you could solve this by simply concatenating two strings, and then slice it back down to 8 characters again.
A better solution
Though, please be aware that Math.random() was never designed or meant to be cryptographically secure. Since you only want passwords 8 characters long, I assume you're not interested in this in any case. However, for reference (and everyone else), I'll show a solution based on an actual CSPRNG. The idea is the same, we're just utilizing window.crypto instead.
window.crypto.getRandomValues(new BigUint64Array(1))[0].toString(36)
Here we are generating 1 word with 64 bits of random data, and cast it to a base36 string (0-9 and a-z). It should give you a truly random string roughly 10-13 characters long.
Extending the solution
However, to make it more secure we also want it to be longer and with mixed upper and lower cases.
We could do this either by just repeating the process twice:
let strings = window.crypto.getRandomValues(new BigUint64Array(2));
console.log(strings[0].toString(36) + strings[1].toString(36).toUpperCase());
Or we could make a fancy generic generator which uses Array.reduce to concatenate multiple random 64 bit words, alternating between uppercasing each stanza:
window.crypto.getRandomValues(new BigUint64Array(length)).reduce(
(prev, curr, index) => (
!index ? prev : prev.toString(36)
) + (
index % 2 ? curr.toString(36).toUpperCase() : curr.toString(36)
)
);
length is the number of 64 bit words to join. I generally use 4, which gives me rougly 48-52 random alphanumeric characters, upper and lower cased.
If you specifically want "special characters" included, you can optionally replace the 0-9 numbers in the uppercase stanzas with a simple replace() call.
const regx = new RegExp(/\d/, "g");
window.crypto.getRandomValues(new BigUint64Array(length)).reduce(
(prev, curr, index) => (
!index ? prev : prev.toString(36)
) + (
index % 2 ? curr.toString(36).toUpperCase().replace(regx, key => ".,:;-_()=*".charAt(key)) : curr.toString(36)
)
);
You may also optionally shuffle the final order, which is easily accomplished with this chaining "oneliner"
password.split('').sort(
() => 128 - window.crypto.getRandomValues(new Uint8Array(1))[0]
).join('')
The idea here is to split the generated string into an array of characters, and then sort that character array with cryptographical randomness, and finally joining it back into a string.
Personally, I have this little bookmarklet saved in my browser bookmarks bar, for quick and easy access whenever I need to generate a site-specific username:
javascript:(
function(){
prompt('Here is your shiny new random string:',
window.crypto.getRandomValues(new BigUint64Array(4)).reduce(
(prev, curr, index) => (
!index ? prev : prev.toString(36)
) + (
index % 2 ? curr.toString(36).toUpperCase() : curr.toString(36)
)
).split('').sort(() => 128 -
window.crypto.getRandomValues(new Uint8Array(1))[0]
).join('')
);
}
)();
Compatibility notices
BigUint64Array was added in:
Chrome/Chromium 67 in May 2018
Node 10.4 in June 2018
Firefox 68 in July 2019
Edge 79 in January 2020 (the first stable Chromium-based Edge release)
The final ECMAScript 2020 specification (ES11) in June 2020
and finally Safari 15 in September 2021.
Other JS engines are tracked on Can I Use or MDN Compatibility Table
Crypto.getRandomValues() has better support (except for Node):
Chrome 11
Edge 12
Firefox 21
Safari 5
Node 15.0
So if you're still on team IE 11 or use end-of-life node versions, you're stuck with using a polyfill, math.round() or a workaround with other types such as BigUInt32Array.
function password_generator( len ) {
var length = (len)?(len):(10);
var string = "abcdefghijklmnopqrstuvwxyz"; //to upper
var numeric = '0123456789';
var punctuation = '!##$%^&*()_+~`|}{[]\:;?><,./-=';
var password = "";
var character = "";
var crunch = true;
while( password.length<length ) {
entity1 = Math.ceil(string.length * Math.random()*Math.random());
entity2 = Math.ceil(numeric.length * Math.random()*Math.random());
entity3 = Math.ceil(punctuation.length * Math.random()*Math.random());
hold = string.charAt( entity1 );
hold = (password.length%2==0)?(hold.toUpperCase()):(hold);
character += hold;
character += numeric.charAt( entity2 );
character += punctuation.charAt( entity3 );
password = character;
}
password=password.split('').sort(function(){return 0.5-Math.random()}).join('');
return password.substr(0,len);
}
console.log( password_generator() );
This generates a little more robust password that should pass any password strength test. eg: f1&d2?I4(h1&, C1^y1)j1#G2#, j2{h6%b5#R2)
This is my function for generating a 8-character crypto-random password:
function generatePassword() {
var buf = new Uint8Array(6);
window.crypto.getRandomValues(buf);
return btoa(String.fromCharCode.apply(null, buf));
}
What it does: Retrieves 6 crypto-random 8-bit integers and encodes them with Base64.
Since the result is in the Base64 character set the generated password may consist of A-Z, a-z, 0-9, + and /.
function generatePass(pLength){
var keyListAlpha="abcdefghijklmnopqrstuvwxyz",
keyListInt="123456789",
keyListSpec="!##_",
password='';
var len = Math.ceil(pLength/2);
len = len - 1;
var lenSpec = pLength-2*len;
for (i=0;i<len;i++) {
password+=keyListAlpha.charAt(Math.floor(Math.random()*keyListAlpha.length));
password+=keyListInt.charAt(Math.floor(Math.random()*keyListInt.length));
}
for (i=0;i<lenSpec;i++)
password+=keyListSpec.charAt(Math.floor(Math.random()*keyListSpec.length));
password=password.split('').sort(function(){return 0.5-Math.random()}).join('');
return password;
}
code to generate a password with a given length (default to 8) and have at least one upper case, one lower, one number and one symbol
(2 functions and one const variable called 'Allowed')
const Allowed = {
Uppers: "QWERTYUIOPASDFGHJKLZXCVBNM",
Lowers: "qwertyuiopasdfghjklzxcvbnm",
Numbers: "1234567890",
Symbols: "!##$%^&*"
}
const getRandomCharFromString = (str) => str.charAt(Math.floor(Math.random() * str.length))
/**
* the generated password will be #param length, which default to 8,
* and will have at least one upper, one lower, one number and one symbol
* #param {number} length - password's length
* #returns a generated password
*/
const generatePassword = (length = 8) => {
let pwd = "";
pwd += getRandomCharFromString(Allowed.Uppers); // pwd will have at least one upper
pwd += getRandomCharFromString(Allowed.Lowers); // pwd will have at least one lower
pwd += getRandomCharFromString(Allowed.Numbers); // pwd will have at least one number
pwd += getRandomCharFromString(Allowed.Symbols); // pwd will have at least one symbol
for (let i = pwd.length; i < length; i++)
pwd += getRandomCharFromString(Object.values(Allowed).join('')); // fill the rest of the pwd with random characters
return pwd
}
A modern and secure solution
Be aware of answers that rely on Math.random - they are not secure. This is an old question so it's no surprise that Math.random still pops up, but you should absolutely not be using it to generate a string to secure anything. If you really need to support browsers older than IE11, you should add a fallback to get the random values from the back-end, generated using a CSPRNG.
function generatePassword(length) {
const crypto = window.crypto || window.msCrypto;
if (typeof crypto === 'undefined') {
throw new Error('Crypto API is not supported. Please upgrade your web browser');
}
const charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const indexes = crypto.getRandomValues(new Uint32Array(length));
let secret = '';
for (const index of indexes) {
secret += charset[index % charset.length];
}
return secret;
}
This is a simple example. You'd probably want to add special characters to the set and maybe enforce digits or symbols to be present.
If you have lodash >= 4.0 in place there is a more elegant way of doing it
var chars = 'abcdefghkmnpqrstuvwxyz23456789';
function generatePassword(length) {
return _.sampleSize(chars, length).join('');
}
Here's my take (with Typescript) on this using the browser crypto API and enforcing a password which has at least:
1 lower case letter
1 upper case letter
1 symbol
const LOWER_CASE_CHARS = 'abcdefghijklmnopqrstuvwxyz'.split('');
const UPPER_CASE_CHARS = LOWER_CASE_CHARS.map((x) => x.toUpperCase());
const SYMBOLS = '!£$%^&*()#~:;,./?{}=-_'.split('');
const LETTERS_MIX = [...LOWER_CASE_CHARS, ...UPPER_CASE_CHARS, ...SYMBOLS];
const CHARS_LENGTH = LETTERS_MIX.length;
function containsLowerCase(str: string): boolean {
return LOWER_CASE_CHARS.some((x) => str.includes(x));
}
function containsUpperCase(str: string): boolean {
return UPPER_CASE_CHARS.some((x) => str.includes(x));
}
function containsSymbol(str: string): boolean {
return SYMBOLS.some((x) => str.includes(x));
}
function isValidPassword(password: string) {
return containsLowerCase(password) && containsUpperCase(password) && containsSymbol(password);
}
export function generateStrongPassword(length: number = 16): string {
const buff = new Uint8Array(length);
let generatedPassword = '';
do {
window.crypto.getRandomValues(buff);
generatedPassword = [...buff].map((x) => LETTERS_MIX[x % CHARS_LENGTH]).join('');
} while (!isValidPassword(generatedPassword));
return generatedPassword;
}
This will produce a realistic password if having characters [\]^_ is fine. Requires lodash and es7
String.fromCodePoint(...range(8).map(() => Math.floor(Math.random() * 57) + 0x41))
and here's without lodash
String.fromCodePoint(...Array.from({length: 8}, () => Math.floor(Math.random() * 57) + 65))
Here is a function provides you more options to set min of special chars, min of upper chars, min of lower chars and min of number
function randomPassword(len = 8, minUpper = 0, minLower = 0, minNumber = -1, minSpecial = -1) {
let chars = String.fromCharCode(...Array(127).keys()).slice(33),//chars
A2Z = String.fromCharCode(...Array(91).keys()).slice(65),//A-Z
a2z = String.fromCharCode(...Array(123).keys()).slice(97),//a-z
zero2nine = String.fromCharCode(...Array(58).keys()).slice(48),//0-9
specials = chars.replace(/\w/g, '')
if (minSpecial < 0) chars = zero2nine + A2Z + a2z
if (minNumber < 0) chars = chars.replace(zero2nine, '')
let minRequired = minSpecial + minUpper + minLower + minNumber
let rs = [].concat(
Array.from({length: minSpecial ? minSpecial : 0}, () => specials[Math.floor(Math.random() * specials.length)]),
Array.from({length: minUpper ? minUpper : 0}, () => A2Z[Math.floor(Math.random() * A2Z.length)]),
Array.from({length: minLower ? minLower : 0}, () => a2z[Math.floor(Math.random() * a2z.length)]),
Array.from({length: minNumber ? minNumber : 0}, () => zero2nine[Math.floor(Math.random() * zero2nine.length)]),
Array.from({length: Math.max(len, minRequired) - (minRequired ? minRequired : 0)}, () => chars[Math.floor(Math.random() * chars.length)]),
)
return rs.sort(() => Math.random() > Math.random()).join('')
}
randomPassword(12, 1, 1, -1, -1)// -> DDYxdVcvIyLgeB
randomPassword(12, 1, 1, 1, -1)// -> KYXTbKf9vpMu0
randomPassword(12, 1, 1, 1, 1)// -> hj|9)V5YKb=7
Gumbo's solution does not work. This one does though:
function makePasswd() {
var passwd = '';
var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
for (i=1;i<8;i++) {
var c = Math.floor(Math.random()*chars.length + 1);
passwd += chars.charAt(c)
}
return passwd;
}
Randomly assigns Alpha, Numeric, Caps and Special per character then validates the password. If it doesn't contain each of the above, randomly assigns a new character from the missing element to a random existing character then recursively validates until a password is formed:
function createPassword(length) {
var alpha = "abcdefghijklmnopqrstuvwxyz";
var caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numeric = "0123456789";
var special = "!$^&*-=+_?";
var options = [alpha, caps, numeric, special];
var password = "";
var passwordArray = Array(length);
for (i = 0; i < length; i++) {
var currentOption = options[Math.floor(Math.random() * options.length)];
var randomChar = currentOption.charAt(Math.floor(Math.random() * currentOption.length));
password += randomChar;
passwordArray.push(randomChar);
}
checkPassword();
function checkPassword() {
var missingValueArray = [];
var containsAll = true;
options.forEach(function (e, i, a) {
var hasValue = false;
passwordArray.forEach(function (e1, i1, a1) {
if (e.indexOf(e1) > -1) {
hasValue = true;
}
});
if (!hasValue) {
missingValueArray = a;
containsAll = false;
}
});
if (!containsAll) {
passwordArray[Math.floor(Math.random() * passwordArray.length)] = missingValueArray.charAt(Math.floor(Math.random() * missingValueArray.length));
password = "";
passwordArray.forEach(function (e, i, a) {
password += e;
});
checkPassword();
}
}
return password;
}
I see much examples on this page are using Math.random. This method hasn't cryptographically strong random values so it's unsecure. Instead Math.random recomended use getRandomValues or your own alhorytm.
You can use passfather. This is a package that are using much cryptographically strong alhorytmes. I'm owner of this package so you can ask some question.
passfather
I got insprired by the answers above (especially by the hint from #e.vyushin regarding the security of Math.random() ) and I came up with the following solution that uses the crypto.getRandomValues() to generate a rondom array of UInt32 values with the length of the password length.
Then, it loops through the array and devides each element by 2^32 (max value of a UInt32) to calculate the ratio between the actual value and the max. possible value. This ratio is then mapped to the charset string to determine which character of the string is picked.
console.log(createPassword(16,"letters+numbers+signs"));
function createPassword(len, charset) {
if (charset==="letters+numbers") {
var chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
} else if (charset==="letters+numbers+signs") {
var chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!§$%&/?#+-_#";
}
var arr = new Uint32Array(len);
var maxRange = Math.pow(2,32);
var passwd = '';
window.crypto.getRandomValues(arr);
for (let i=0;i<len;i++) {
var c = Math.floor(arr[i] / maxRange * chars.length + 1);
passwd += chars.charAt(c);
}
return passwd;
}
Thus, the code is able to use the advantage of the crypto-Class (improved security for the random value generation) and is adaptable to use any kind of charset the user wished. A next step would be to use regular expression strings to define the charset to be used.
Generate a random password of length 8 to 32 characters with at least 1 lower case, 1 upper case, 1 number, 1 special char (!#$&)
function getRandomUpperCase() {
return String.fromCharCode( Math.floor( Math.random() * 26 ) + 65 );
}
function getRandomLowerCase() {
return String.fromCharCode( Math.floor( Math.random() * 26 ) + 97 );
}
function getRandomNumber() {
return String.fromCharCode( Math.floor( Math.random() * 10 ) + 48 );
}
function getRandomSymbol() {
// const symbol = '!##$%^&*(){}[]=<>/,.|~?';
const symbol = '!#$&';
return symbol[ Math.floor( Math.random() * symbol.length ) ];
}
const randomFunc = [ getRandomUpperCase, getRandomLowerCase, getRandomNumber, getRandomSymbol ];
function getRandomFunc() {
return randomFunc[Math.floor( Math.random() * Object.keys(randomFunc).length)];
}
function generatePassword() {
let password = '';
const passwordLength = Math.random() * (32 - 8) + 8;
for( let i = 1; i <= passwordLength; i++ ) {
password += getRandomFunc()();
}
//check with regex
const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{8,32}$/
if( !password.match(regex) ) {
password = generatePassword();
}
return password;
}
console.log( generatePassword() );
here is a simply smart code :
function generate(l) {
if (typeof l==='undefined'){var l=8;}
/* c : alphanumeric character string */
var c='abcdefghijknopqrstuvwxyzACDEFGHJKLMNPQRSTUVWXYZ12345679',
n=c.length,
/* p : special character string */
p='!##$+-*&_',
o=p.length,
r='',
n=c.length,
/* s : determinate the position of the special character */
s=Math.floor(Math.random() * (p.length-1));
for(var i=0; i<l; ++i){
if(s == i){
/* special charact insertion (random position s) */
r += p.charAt(Math.floor(Math.random() * o));
}else{
/* alphanumeric insertion */
r += c.charAt(Math.floor(Math.random() * n));
}
}
return r;
}
Simply call generate(), and it do key containing one special character (!##$+-*&_) for security.
Possible results : WJGUk$Ey, gaV7#fF7, ty_T55DD, YtrQMWveZqYyYKo_
There is more details and example in my website : https://www.bxnxg.com/minituto-01-generer-mots-de-passes-secures-facilements-en-javascript/
Stop the madness!
My pain point is that every Sign-Up tool allows a different set of special characters. Some might only allow these ##$%&* while others maybe don't allow * but do allow other things. Every password generator I've come across is binary when it comes to special characters. It allows you to either include them or not. So I wind up cycling through tons of options and scanning for outliers that don't meet the requirements until I find a password that works. The longer the password the more tedious this becomes. Finally, I have noticed that sometimes Sign-Up tools don't let you repeat the same character twice in a row but password generators don't seem to account for this. It's madness!
I made this for myself so I can just paste in the exact set of special characters that are allowed. I do not pretend this is elegant code. I just threw it together to meet my needs.
Also, I couldn't think of a time when a Sign-Up tool did not allow numbers or wasn't case sensitive so my passwords always have at least one number, one upper case letter, one lower case letter, and one special character. This means the minimum length is 4. Technically I can get around the special character requirement by just entering a letter if need be.
const getPassword = (length, arg) => {
length = document.getElementById("lengthInput").value || 16;
arg = document.getElementById("specialInput").value || "~!##$%^&*()_+-=[]{}|;:.,?><";
if (length < 4) {
updateView("passwordValue", "passwordValue", "", "P", "Length must be at least 4");
return console.error("Length must be at least 4")
} else if (length > 99) {
updateView("passwordValue", "passwordValue", "", "P", "Length must be less then 100");
return console.error("Length must be less then 100")
}
const lowercase = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
const uppercase = lowercase.join("").toUpperCase().split("");
const specialChars = arg.split("").filter(item => item.trim().length);
const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let hasNumber = false;
let hasUpper = false;
let hasLower = false;
let hasSpecial = false;
if (Number(length)) {
length = Number(length)
} else {
return console.error("Enter a valid length for the first argument.")
}
let password = [];
let lastChar;
for (let i = 0; i < length; i++) {
let char = newChar(lowercase, uppercase, numbers, specialChars);
if (char !== lastChar) {
password.push(char);
lastChar = char
if (Number(char)) {
hasNumber = true
}
if (lowercase.indexOf(char) > -1) {
hasLower = true
}
if (uppercase.indexOf(char) > -1) {
hasUpper = true
}
if (specialChars.indexOf(char) > -1) {
hasSpecial = true
}
} else {
i--
}
if (i === length - 1 && (!hasNumber || !hasUpper || !hasLower || !hasSpecial)) {
hasNumber = false;
hasUpper = false;
hasLower = false;
hasSpecial = false;
password = [];
i = -1;
}
}
function newChar(lower, upper, nums, specials) {
let set = [lower, upper, nums, specials];
let pick = set[Math.floor(Math.random() * set.length)];
return pick[Math.floor(Math.random() * pick.length)]
}
updateView("passwordValue", "passwordValue", "", "P", password.join(""));
updateView("copyPassword", "copyPassword", "", "button", "copy text");
document.getElementById("copyPassword").addEventListener("click", copyPassword);
}
const copyPassword = () => {
let text = document.getElementById("passwordValue").textContent;
navigator.clipboard.writeText(text);
};
const updateView = (targetId, newId, label, element, method = '') => {
let newElement = document.createElement(element);
newElement.id = newId;
let content = document.createTextNode(label + method);
newElement.appendChild(content);
let currentElement = document.getElementById(targetId);
let parentElement = currentElement.parentNode;
parentElement.replaceChild(newElement, currentElement);
}
document.getElementById("getPassword").addEventListener("click", getPassword);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div>
<button id="getPassword">Generate Password</button>
<input type="number" id="lengthInput" placeholder="Length">
<input type="text" id="specialInput" placeholder="Special Characters">
<p id="passwordValue"></p>
<p id="copyPassword"></p>
</div>
</body>
</html>
even shorter:
Array.apply(null, Array(8)).map(function() {
var c = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
return c.charAt(Math.random() * c.length);
}).join('');
or as function:
function generatePassword(length, charSet) {
charSet = charSet ? charSet : 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789^°!"§$%&/()=?`*+~\'#,;.:-_';
return Array.apply(null, Array(length || 10)).map(function() {
return charSet.charAt(Math.random() * charSet.length);
}).join('');
}
function genPass(n) // e.g. pass(10) return 'unQ0S2j9FY'
{
let c='abcdefghijklmnopqrstuvwxyz'; c+=c.toUpperCase()+1234567890;
return [...Array(n)].map(b=>c[~~(Math.random()*62)]).join('')
}
Where n is number of output password characters; 62 is c.length and where e.g. ~~4.5 = 4 is trick for replace Math.floor
Alternative
function genPass(n) // e.g. pass(10) return 'unQ0S2j9FY'
{
let c='abcdefghijklmnopqrstuvwxyz'; c+=c.toUpperCase()+1234567890;
return '-'.repeat(n).replace(/./g,b=>c[~~(Math.random()*62)])
}
to extend characters list, add them to c e.g. to add 10 characters !$^&*-=+_? write c+=c.toUpperCase()+1234567890+'!$^&*-=+_?' and change Math.random()*62 to Math.random()*72 (add 10 to 62).
This method gives the options to change size and charset of your password.
function generatePassword(length=8, charset="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") {
return new Array(length)
.fill(null)
.map(()=> charset.charAt(Math.floor(Math.random() * charset.length)))
.join('');
}
console.log(generatePassword()); // 02kdFjzX
console.log(generatePassword(4)); // o8L5
console.log(generatePassword(16)); // jpPd7S09txv9b02p
console.log(generatePassword(16, "abcd1234")); // 4c4d323a31c134dd
A simple lodash solution that warranties 14 alpha, 3 numeric and 3 special characters, not repeated:
const generateStrongPassword = (alpha = 14, numbers = 3, special = 3) => {
const alphaChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const numberChars = '0123456789';
const specialChars = '!"£$%^&*()-=+_?';
const pickedChars = _.sampleSize(alphaChars, alpha)
.concat(_.sampleSize(numberChars, numbers))
.concat(_.sampleSize(specialChars, special));
return _.shuffle(pickedChars).join('');
}
const myPassword = generateStrongPassword();
I also developed my own password generator, with random length (between 16 and 40 by default), strong passwords, maybe it could help.
function randomChar(string) {
return string[Math.floor(Math.random() * string.length)];
}
// you should use another random function, like the lodash's one.
function random(min = 0, max = 1) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// you could use any shuffle function, the lodash's one, or the following https://stackoverflow.com/a/6274381/6708504
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
function generatePassword() {
const symbols = '§±!##$%^&*()-_=+[]{}\\|?/<>~';
const numbers = '0123456789';
const lowercaseLetters = 'abcdefghijklmnopqrstuvwxyz';
const uppercaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const minCharsGroup = 4;
const maxCharsGroup = 10;
const randomSymbols = [...Array(random(minCharsGroup, maxCharsGroup))].map(() => randomChar(symbols));
const randomNumbers = [...Array(random(minCharsGroup, maxCharsGroup))].map(() => randomChar(numbers));
const randomUppercasesLetters = [...Array(random(minCharsGroup, maxCharsGroup))].map(() => randomChar(uppercaseLetters));
const randomLowercasesLetters = [...Array(random(minCharsGroup, maxCharsGroup))].map(() => randomChar(lowercaseLetters));
const chars = [...randomSymbols, ...randomNumbers, ...randomUppercasesLetters, ...randomLowercasesLetters];
return shuffle(chars).join('');
}
const alpha = 'abcdefghijklmnopqrstuvwxyz';
const calpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const num = '1234567890';
const specials = ',.!##$%^&*';
const options = [alpha, alpha, alpha, calpha, calpha, num, num, specials];
let opt, choose;
let pass = "";
for ( let i = 0; i < 8; i++ ) {
opt = Math.floor(Math.random() * options.length);
choose = Math.floor(Math.random() * (options[opt].length));
pass = pass + options[opt][choose];
options.splice(opt, 1);
}
console.log(pass);
Length 8 characters
At least 1 Capital
At least 1 Number
At least 1 Special Character
Here's another approach based off Stephan Hoyer's solution
var _ = require('lodash');
function getRandomString(length) {
var chars = 'abcdefghkmnpqrstuvwxyz23456789';
return _.times(length, () => sample(chars)).join('');
}
Update: replacing the core Math.random() by crypto.getRandomValues and add options
Solution with scrambling:
const Allowed = {
Uppers: 'QWERTYUIOPASDFGHJKLZXCVBNM',
Lowers: 'qwertyuiopasdfghjklzxcvbnm',
Numbers: '1234567890',
Symbols: '!##$%^&*'
}
const AllowedUpperArray = Array.from(Allowed.Uppers)
const AllowedLowerArray = Array.from(Allowed.Lowers)
const AllowedNumberArray = Array.from(Allowed.Numbers)
const AllowedSymbolArray = Array.from(Allowed.Symbols)
function getCharAt(charArray, index) {
return charArray[index % charArray.length]
}
function scrambleArray(chars) {
return chars.sort(() => Math.random() - 0.5)
}
function getAllowedChars(compositionRule = {}) {
let chars = []
if (!compositionRule.upperCase?.forbidden) chars = chars.concat(AllowedUpperArray)
if (!compositionRule.lowerCase?.forbidden) chars = chars.concat(AllowedLowerArray)
if (!compositionRule.numbers?.forbidden) chars = chars.concat(AllowedNumberArray)
if (!compositionRule.symbols?.forbidden) chars = chars.concat(AllowedSymbolArray)
return chars
}
function assertAreRulesValid(compositionRule) {
const {
upperCase,
lowerCase,
numbers,
symbols
} = compositionRule
if (length < 1) throw new Error('length < 1')
if (upperCase?.min < 0) throw new Error('upperCase.min < 0')
if (lowerCase?.min < 0) throw new Error('lowerCase.min < 0')
if (numbers?.min < 0) throw new Error('numbers.min < 0')
if (symbols?.min < 0) throw new Error('symbols.min < 0')
if (length && length < (upperCase?.min || 0 + lowerCase?.min || 0 + numbers?.min || 0 + symbols?.min || 0)) throw new Error('length < sum of min')
if (upperCase?.forbidden && lowerCase?.forbidden && numbers?.forbidden && symbols?.forbidden) throw new Error('no char type allowed')
if (upperCase?.forbidden && upperCase?.min) throw new Error('forbidden incompatible with min')
if (lowerCase?.forbidden && lowerCase?.min) throw new Error('forbidden incompatible with min')
if (symbols?.forbidden && symbols?.min) throw new Error('forbidden incompatible with min')
if (numbers?.forbidden && numbers?.min) throw new Error('forbidden incompatible with min')
}
/**
* Generates password of the given length with at least one upper, one lower, one number and one symbol.
* #param length length of the password, min 4
* #throws Error if length is less than 4
*/
function generatePassword(length = 8, compositionRule = {}) {
const {
upperCase,
lowerCase,
numbers,
symbols
} = compositionRule
const indexes = crypto.getRandomValues(new Uint32Array(length));
const chars = []
let i = 0
let lastIndex = i
while (i < upperCase?.min || 0) chars.push(getCharAt(AllowedUpperArray, indexes[i++]))
while (i < lastIndex + lowerCase?.min || 0) chars.push(getCharAt(AllowedLowerArray, indexes[i++]))
lastIndex = i
while (i < lastIndex + numbers?.min || 0) chars.push(getCharAt(AllowedNumberArray, indexes[i++]))
lastIndex = i
while (i < lastIndex + symbols?.min || 0) chars.push(getCharAt(AllowedSymbolArray, indexes[i++]))
const allowedChars = getAllowedChars(compositionRule)
while (i < length || 0) chars.push(getCharAt(allowedChars, indexes[i++]))
return scrambleArray(chars).join('')
}
const opt1 = {
upperCase: { min: 3 },
lowerCase: { forbidden: true },
numbers: { min: 2 },
symbols: { min: 1 }
}
const pwd1 = generatePassword(10, opt1)
console.log('10 characters, min 3 uppercase, 2 numbers, 1 symbol and no lowercase:', pwd1)
const opt2 = {
upperCase: { forbidden: true },
lowerCase: { forbidden: true },
numbers: { forbidden: true },
symbols: { min: 1 }
}
const pwd2 = generatePassword(5, opt2)
console.log('5 characters, min 1 symbol but upperCase, lowercase, and numbers forbidden:', pwd2)
Answers so far are overly complicated or use Math.random() or depend on another package.
I feel the world needs yet another password generator :-)
/**
* #param {number} length
* #returns {string}
*/
function generateRandomPassword(length) {
const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
return window.crypto.getRandomValues(new Uint8Array(length)).reduce((password, number) => {
return password + charset.charAt(number % charset.length);
}, "");
}
Valid characters are fixed but can be trivially tailored. Probability of having a digit can be increased by repeating the sequence in the charset (i.e: charset = "…vwxyz01234567890123456789").
It uses the secure getRandomValues().
It doesn't ensure the password contains at least one uppercase letter, one lowercase letter and one digit. Therefore, it might generate a real word/noun or even an offensive word. It is very unlikely with longer passwords, though. Skewing toward digits (as explained above) may not solve that issue due to l33t. Adding some special characters is the safest course if that is your concern.
PS: Should charset be more than 256 characters long, the code must use Uint16Array instead.
PPS: What's wrong with Math.random(): it is pseudo-random. The sequence is somewhat predictable. Not every possible theoretical password can be generated because the next character is determined from a computed sequence.
Here's a free, configurable Javascript class generating random passwords: Javascript Random Password Generator.
Examples
Password consisting of Lower case + upper case + numbers, 8 characters long:
var randomPassword = new RandomPassword();
document.write(randomPassword.create());
Password consisting of Lower case + upper case + numbers, 20 characters long:
var randomPassword = new RandomPassword();
document.write(randomPassword.create(20));
Password consisting of Lower case + upper case + numbers + symbols, 20 characters long:
var randomPassword = new RandomPassword();
document.write(randomPassword.create(20,randomPassword.chrLower+randomPassword.chrUpper+randomPassword.chrNumbers+randomPassword.chrSymbols));
var createPassword = function() {
var passAt = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
var passArray = Array.from({length: 15})
return passArray.map(function(_, index) {
return index % 4 == 3 ? '-' : passAt.charAt(Math.random() * passAt.length)
}).join('')
}
result like:
L5X-La0-bN0-UQO
9eW-svG-OdS-8Xf
ick-u73-2s0-TMX
5ri-PRP-MNO-Z1j
Here's a quick dynamic modern solution which I thought I'll share
const generatePassword = (
passwordLength = 8,
useUpperCase = true,
useNumbers = true,
useSpecialChars = true,
) => {
const chars = 'abcdefghijklmnopqrstuvwxyz'
const numberChars = '0123456789'
const specialChars = '!"£$%^&*()'
const usableChars = chars
+ (useUpperCase ? chars.toUpperCase() : '')
+ (useNumbers ? numberChars : '')
+ (useSpecialChars ? specialChars : '')
let generatedPassword = ''
for(i = 0; i <= passwordLength; i++) {
generatedPassword += usableChars[Math.floor(Math.random() * (usableChars.length))]
}
return generatedPassword
}