Skip to content

Instantly share code, notes, and snippets.

@mebtte
Last active April 21, 2019 07:15
Show Gist options
  • Save mebtte/e1881c8820c1b07a9e471ae88347858a to your computer and use it in GitHub Desktop.
Save mebtte/e1881c8820c1b07a9e471ae88347858a to your computer and use it in GitHub Desktop.
Get a random string.
/**
* Get a random string.
* @author mebtte<mebtte@gamil.com>
* @param {String} [length] The length of string, detault `10`.
* @return {String} A random string.
*/
function getRandomString(length = 10) {
const randomChars = [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"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"
];
const randomCharLength = randomChars.length;
let string = "";
for (let i = 0; i < length; i += 1) {
string += randomChars[Math.floor(randomCharLength * Math.random())];
}
return string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment