Skip to content

Instantly share code, notes, and snippets.

@alexsc6955
Last active November 7, 2022 17:10
Show Gist options
  • Save alexsc6955/0b8096ea06b36c54fdb5f3af1ea1a7f7 to your computer and use it in GitHub Desktop.
Save alexsc6955/0b8096ea06b36c54fdb5f3af1ea1a7f7 to your computer and use it in GitHub Desktop.
Generates a random string with a given lenth
/**
* Generate a random string with a given lenth
*
* @author <@thehomelessdev>
* @version 1.0.1
*
* @example
* // returns ten random characters including numbers and special characters
* generateRandomString(10, { includeSpecialCharacters: true })
*
* @param {number} len number of characters to include in the result
* @param {object} options controls output
* @param[0] {boolean} includeSpecialCharacters If true include special
* characters
* @param[1] {boolean} includeNumbers If true include numbers
*
* @returns {string}
*/
const generateRandomString = (len, options: { includeSpecialCharacters = false, includeNumbers = true }) => {
// extract options with default values
const { includeSpecialCharacters = false, includeNumbers = true } = options
// possible numbers
const _numbers = "0123456789";
// possible special characters (feel free to add whatever special character
// you need
const _specialChars = `!*@.,;:-_+/'?"!|`;
// All possible characters (add _numbers and _specialChars depending on the options)
const _sym = `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz${includeNumbers ? _numbers : ""}${includeSpecialCharacters ? _specialChars : ""}`;
// Initialize result variable as an empty string
let str = "";
// for each time between 0 and the passed length append one of the
// available characters
for (let i = 0; i < len; i++) {
// Math.floor() rounds down and returns the largest integer less than
// or equal to a given number (Math.random() * _sym.length)
// Math.random() return a random float number between 0 and 1 which
// multiply by _sym.length, basicaly selects a random character within _sym.
str += _sym.charAt(Math.floor(Math.random() * _sym.length));
}
return str;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment