Created
June 8, 2017 08:21
-
-
Save s-lyn/8652ce929151fd9a6a43779540d113b3 to your computer and use it in GitHub Desktop.
Generate random string/characters in JavaScript
This file contains hidden or 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 string | |
* @param {number} len Length of string | |
* @param {string} charSet Allowable characters | |
* @return {string} | |
*/ | |
function randomString(len = 10, charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') { | |
let randomString = ''; | |
for (let i = 0; i < len; i++) { | |
let randomPoz = Math.floor(Math.random() * charSet.length); | |
randomString += charSet.substring(randomPoz, randomPoz + 1); | |
} | |
return randomString; | |
} | |
module.exports = randomString; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment