Last active
January 8, 2023 06:24
-
-
Save syahid-dev/03cafd4349f9d81b4b713b538e2b81a5 to your computer and use it in GitHub Desktop.
Generate Random String (JavaScript)
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
const numbers = '0123456789'; | |
const specials = '`-=[]\\;\',./~!@#$%^&*()_+{}|:"<>?'; | |
const charsLower = 'abcdefghijklmnopqrstuvwxyz'; | |
const charsUpper = charsLower.toUpperCase(); | |
const alphabet = charsLower + charsUpper; | |
const alphaNumeric = numbers + alphabet; | |
const all = alphaNumeric + specials; | |
const random = { | |
numbers, | |
specials, | |
charsLower, | |
charsUpper, | |
alphabet, | |
alphaNumeric, | |
all, | |
}; | |
for (const charset in random) { | |
const randomString = generateRandomString(8, random[charset]); | |
console.log(charset, ':', randomString); | |
} |
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
/** | |
* Generate random integer | |
* | |
* @param {number} min Specifies the lowest number to return | |
* @param {number} max Specifies the highest number to return | |
* | |
* @returns {number} A random integer between min and max | |
*/ | |
function getRandomInt(min, max) { | |
return Math.floor(Math.random() * (max - min + 1)) + min; | |
} | |
/** | |
* Generate random string | |
* | |
* @param {number} length Specifies the length of the random string | |
* @param {string} characters define the characters for the string | |
* | |
* @returns {string} | |
*/ | |
function generateRandomString(length, characters) { | |
let result = ''; | |
for (let i = 0; i < length; i++) { | |
const randIndex = getRandomInt(0, characters.length - 1); | |
const randChar = characters[randIndex]; | |
result += randChar; | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment