Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generate a random string of ASCII characters
const generateRandomAsciiString = (len, cap=false, lower=false, num=false, special=false) => {
let str = '';
const includesCap = str => !![...Array(26)]
.map((n, i) => String.fromCharCode(i + 65))
.filter(c => str.includes(c)).length;
const includesLower = str => !![...Array(26)]
.map((n, i) => String.fromCharCode(i + 97))
.filter(c => str.includes(c)).length;
const includesNum = str => !![...Array(10)]
.map((n, i) => String.fromCharCode(i + 48))
.filter(c => str.includes(c)).length;
const includesSpecial = str => !![
...[...Array(15)].map((n, i) => String.fromCharCode(i + 33)),
...[...Array(7)].map((n, i) => String.fromCharCode(i + 58)),
...[...Array(4)].map((n, i) => String.fromCharCode(i + 123)),
].filter(c => str.includes(c)).length;
while (
!str.length ||
!((includesCap(str) || !cap)
&& (includesLower(str) || !lower)
&& (includesNum(str) || !num)
&& (includesSpecial(str) || !special))
) {
str = [...Array(90)]
.map((n, i) => String.fromCharCode(i + 37))
.sort(() => 0.5 - Math.random())
.slice(0,len)
.join('');
}
return str;
};
@kavunshiva

This comment has been minimized.

Copy link
Owner Author

@kavunshiva kavunshiva commented Nov 13, 2018

generates an ASCII string of random length.

inputs

name type description
len integer length of output string, in number of characters
cap boolean whether or not the output string must contain capital letters
lower boolean whether or not the output string must contain lower case letters
num boolean whether or not the output string must contain numerals
special boolean whether or not the output string must contain special characters

example usage

generateRandomAsciiString(10, true, false, true, false);
=> "$0<l#CYv]s"

[...Array(10)].forEach(() => console.log(generateRandomAsciiString(10, true, false, true, false)));
=>
`)(:6<3FKLA`
`V!"/3D6B%E`
`<1jM\h;ABy`
`@3mPVLJ+_q`
`No/0IH4Q>u`
`^o]N)P#7"q`
`Z'(@"%LNr0`
`m#[ReG.6FI`
`s@"MG')4H/`
`!p#S5UKndF`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.