Generating a Random Code with Apps Script
On this page, you will find examples for generating a random string (for example, to generate a random password).
If the Math.random() function is new to you, start with the page generating a random number.
Math.random()
Usage Examples
Generate a random string of 10 characters that can include numbers and letters:
const length = 10;
const characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
let string = '';
for (let i = 0; i < length; i++) {
string += characters[Math.floor(Math.random() * characters.length)];
}
console.log(string); // Example output: U5FsEZqni5
Generate a random string of 15 characters that can include numbers, uppercase letters, and special characters:
const length = 15;
const characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ$@[]^_!"#$%&\'()*+,-./:;{}<>=|~?';
let string = '';
for (let i = 0; i < length; i++) {
string += characters[Math.floor(Math.random() * characters.length)];
}
console.log(string); // Example output: /ZKZQ@$'(%T}!T{
Generate a random string of 10 characters consisting of uppercase letters with a _ in the 4th position:
let string = '';
for (let i = 0; i < 10; i++) {
string += i == 3 ? '_' : 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[Math.floor(Math.random() * 26)];
}
console.log(string); // Example output: BLZ_LQQEDL