Last active
October 1, 2017 19:01
-
-
Save kvendrik/912edc90536c19c0cfc9 to your computer and use it in GitHub Desktop.
Generate a random string with a fixed length
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
function genRandStr(length = 41){ | |
// Math.random returns number with length between 16 and 18 chars | |
// if length below 16 do in one go | |
if (length <= 16) { | |
return Math.random().toString(36).substring(2,length+2); | |
} | |
// else calculate how many iterations we need | |
const iterations = Math.ceil(length / 16); | |
let outputStr = ''; | |
for(let i = 0; i < iterations; i++){ | |
outputStr += Math.random().toString(36).substring(2,18); | |
} | |
// correct length if it's too high | |
if(outputStr.length > length) { | |
outputStr = outputStr.substring(0,length); | |
} | |
return outputStr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment