Skip to content

Instantly share code, notes, and snippets.

@shahzadns
Last active December 21, 2017 23:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shahzadns/ddf9074db1ebbffab294 to your computer and use it in GitHub Desktop.
Save shahzadns/ddf9074db1ebbffab294 to your computer and use it in GitHub Desktop.
To get an array of randomly selected alpha-numeric characters, in JavaScript.
/**
* @title: Random-alphanumeric-strings
* @author: Shahzad Nawaz
* @dated: 7/16/2015.
*/
//e.g #1
var sixLenstrings = getRandomStrings(6, 2);
console.log(sixLenstrings);
// output: ["UlTl14", "JZRbSS"]
//e.g #2
var threeLenstrings = getRandomStrings(3, 7);
console.log(threeLenstrings);
// output: ["gE3", "fO1", "AZT", "W37", "ntA", "E9Q", "hzG"]
//function that returns strings array.
function getRandomStrings(stringLen, totalStrings) {
var item, items, possible;
//possible characters to include in creating random strings - alpha-numeric
possible = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
items = [];
for (var i = 0; i < totalStrings; i++) {
item = "";
for (var c = 0; c < stringLen; c++) {
item += possible.charAt(Math.floor(Math.random() * possible.length));
}
items.push(item);
}
return items;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment