How to generate a string of randomly chosen characters in JS

Share

Overview

In this shot, we will learn to generate a string composed of randomly chosen characters using JavaScript.

We can achieve this using the Math.random() function, which gives a random number between 0 and 1. Let's take a look at an example.

Code

//declare the characters you needed
const chrs ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
//function that returns string
function generateString(length) {
//initialize emtpy string
let result = ' ';
//get given characters length
const charactersLength = chrs.length;
//loop that gives random character for each iteration
for ( let i = 0; i < length; i++ ) {
result += chrs.charAt(Math.floor(Math.random() * charactersLength));
}
//return the generated string
return result;
}
//call function and print the returned string
console.log(generateString(20));

Explanation

In the above code snippet:

  • Line 2: We declare and initialize the string of characters chrs that need to be in the generated string.
  • Line 5: We define a function that takes the length of the string as a parameter and returns the generated string with the given length.
  • Line 8: We declare and initialize an empty string to store each character generated by the for loop in line 14.
  • Line 11: We store the length of the characters that we gave in chrs.
  • Line 14: We have a for loop that iterates until it reaches the string's given length.
  • Line 15: We get each random character for each iteration of the for loop using the Math.random() function.
  • Line 19: We return the generated string.
  • Line 23: We make a function call on the function generateString() and pass the length of the string as a parameter and print the returned string.