Teo
Teo

Reputation: 3442

JavaScript random password with specific format

I would like to generate a random password respecting the following format:

I thought about it and the only thing I could think of is some function that is quite long and ugly. Could you guys offer me a simpler, more efficient way of doing this?

PS: I'm using this function not on the client side, but on the server side, on my Node.js web application.

Upvotes: 1

Views: 3189

Answers (3)

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

How about we place the formats into strings and we can place than into an array, then randomly chose one and randomly chose and item in that sub-array item:

var uppers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var lowers = "abcdefghijklmnopqrstuvwxyz";
var digits = "01234567890";
var all = uppers + lowers + digits;
var choices = [uppers,lowers,digits];
var checks = [];

var password = ""; 
var ranLength = Math.ceil(Math.random()*10)+3;
for(var i=0; i<ranLength; i++){
    var choice = choices[Math.ceil(Math.random()*3)-1];
    var choiceItem = choice[Math.ceil(Math.random()*(choice.length))-1]
    password += choiceItem;
}

for(var i=0; i<3; i++){ // Append needed values to end
    var choice = choices[i]; 
    var choiceItem = choice[Math.ceil(Math.random()*(choice.length))-1] 
    password += choiceItem;
}

password = password.split('').sort(function(){
    return 0.5 - Math.random(); 
}).join('');

alert(password);

Edited: Sorry made a small mistake. Fixed.

Upvotes: 1

vkurchatkin
vkurchatkin

Reputation: 13570

Here is my solution:

/**
 * sets of charachters
 */
var upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
var lower = 'abcdefghijklmnopqrstuvwxyz'
var digit = '0123456789'
var all = upper + lower + digit

/**
 * generate random integer not greater than `max`
 */

function rand (max) {
  return Math.floor(Math.random() * max)
}

/**
 * generate random character of the given `set`
 */

function random (set) {
  return set[rand(set.length - 1)]
}

/**
 * generate an array with the given `length` 
 * of characters of the given `set`
 */

function generate (length, set) {
  var result = []
  while (length--) result.push(random(set))
  return result
}

/**
 * shuffle an array randomly
 */
function shuffle (arr) {
  var result = []

  while (arr.length) {
    result = result.concat(arr.splice(rand[arr.length - 1]))
  }

  return result
}
/**
 * do the job
 */
function password (length) {
  var result = [] // we need to ensure we have some characters

  result = result.concat(generate(1, upper)) // 1 upper case
  result = result.concat(generate(1, lower)) // 1 lower case
  result = result.concat(generate(1, digit)) // 1 digit
  result = result.concat(generate(length - 3, all)) // remaining - whatever

  return shuffle(result).join('') // shuffle and make a string
}

console.log(password(6))

Upvotes: 7

Rahul Sahu
Rahul Sahu

Reputation: 284

Try this...

var randomstring = Math.random().toString(36).slice(-8);

Upvotes: -2

Related Questions