Skip to content

Instantly share code, notes, and snippets.

@haliphax
Created October 30, 2023 21:17
Show Gist options
  • Save haliphax/88ca8ae949c9d2de17b6fee4cf96cb66 to your computer and use it in GitHub Desktop.
Save haliphax/88ca8ae949c9d2de17b6fee4cf96cb66 to your computer and use it in GitHub Desktop.
generate random string
/** printable ASCII characters */
const ascii = [];
for (let i = 33; i <= 126; ascii.push(String.fromCharCode(i++)));
/** generate random string */
const randomString = limit => {
const result = [];
for (let i = 0; i < limit; i++) {
const index = Math.floor(Math.random() * (126 - 33) + 33);
result.push(ascii[index]);
}
return result.join("");
};
// example usage
randomString(8); // 8 characters
randomString(16); // 16 characters
randomString(32); // 32 characters
randomString(64); // 64 characters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment