Monday 22 April 2019

Generate random string/characters in JavaScript



I want a 5 character string composed of characters picked randomly from the set [a-zA-Z0-9].



What's the best way to do this with JavaScript?


Answer



I think this will work for you:





function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}

console.log(makeid(5));




No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...