Kanchan
Kanchan

Reputation: 65

Generate random password using Google app script

I am using below function to generate random string. But if i run this twice, it will give the string as new string=old string+oldstring

But i need a unique string of same size. How can i do this??

  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%&<>*-";

  for(var j=2;j<=data.length;j++){

  for(var i=0;i<length;i++){
  text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  ss.getRange(j,2).setValue(text);
  Logger.log(text);
  }

Upvotes: 0

Views: 2820

Answers (1)

Alan Wells
Alan Wells

Reputation: 31300

The variable text needs to be reset on every loop:

function generateRandom() {
  var data = "ldk";
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%&<>*-";

  for(var j=2;j<=data.length;j++){
    text = ""; //Reset text to empty string

    for(var i=0;i<possible.length;i++){
      text += possible.charAt(Math.floor(Math.random() * possible.length));
    }

    //ss.getRange(j,2).setValue(text);
    Logger.log(text);
  }
}

Upvotes: 1

Related Questions