Skip to content

Instantly share code, notes, and snippets.

@kvendrik
Last active October 1, 2017 19:01
Show Gist options
  • Save kvendrik/912edc90536c19c0cfc9 to your computer and use it in GitHub Desktop.
Save kvendrik/912edc90536c19c0cfc9 to your computer and use it in GitHub Desktop.
Generate a random string with a fixed length
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