Created
October 30, 2023 21:17
-
-
Save haliphax/88ca8ae949c9d2de17b6fee4cf96cb66 to your computer and use it in GitHub Desktop.
generate random string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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