The first thing you will want to do is create a helper function that can grab a random value from an array.
getRandomValue(array) {
const min = 0; // an integer
const max = array.length; // guaranteed to be an integer
/*
Math.random() will return a random number [0, 1) Notice here that it does not include 1 itself
So basically it is from 0 to .9999999999999999
We multiply this random number by the difference between max and min (max - min). Here our min is always 0.
so now we are basically getting a value from 0 to just less than array.length
BUT we then call Math.floor on this function which returns the given number rounded down to the nearest integer
So Math.floor(Math.random() * (max - min)) returns 0 to array.length - 1
This gives us a random index in the array
*/
const randomIndex = Math.floor(Math.random() * (max - min)) + min;
// then we grab the item that is located at that random index and return it
return array[randomIndex];
}
You could use this helper function with no regard for changing the length of the string, like this:
var randomString = getRandomValue(charset) + getRandomValue(charset) + getRandomValue(charset);
However, you may want to create another function that contains a loop based on how long you want the random string to be:
function getRandomString(charset, length) {
var result = '';
for (var i = 0; i <= length; i++) {
result += getRandomValue(charset);
}
return result;
}
And that function would be used like this
var randomString = getRandomString(charset, 3);