Skip to content

Instantly share code, notes, and snippets.

@renomureza
Last active December 14, 2020 11:25
Show Gist options
  • Save renomureza/d3d9dae08cf46cccbd374354acf51c38 to your computer and use it in GitHub Desktop.
Save renomureza/d3d9dae08cf46cccbd374354acf51c38 to your computer and use it in GitHub Desktop.
Javascript random string generator with dynamic length and characters type.
/**
* @link https://stackoverflow.com/a/1349426/11340631
*/
const makeRandomString = (length = 5, typeCharacter = "lowerUpperNumber") => {
if (length < 5) return "Length must be more than 5.";
if (
typeCharacter !== "lower" &&
typeCharacter !== "upper" &&
typeCharacter !== "number" &&
typeCharacter !== "lowerUpper" &&
typeCharacter !== "lowerNumber" &&
typeCharacter !== "upperNumber" &&
typeCharacter !== "lowerUpperNumber"
) {
return "Character type does not match.";
}
let characters = "";
const lower = "abcdefghijklmnopqrstuvwxyz";
const upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const number = "0123456789";
if (typeCharacter === "lower") {
characters = lower;
}
if (typeCharacter === "upper") {
characters = upper;
}
if (typeCharacter === "number") {
characters = number;
}
if (typeCharacter === "lowerUpper") {
characters = lower + upper;
}
if (typeCharacter === "lowerNumber") {
characters = lower + number;
}
if (typeCharacter === "upperNumber") {
characters = upper + number;
}
if (typeCharacter === "lowerUpperNumber") {
characters = lower + upper + number;
}
let result = "";
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment