In this article, we will create JavaScript functions to accomplish the following functionalities:
- Generate a random letter from the ASCII characters.
- Generate a random string of a given length.
- Generate random strings with special characters.
1) Generate strings from random ASCII characters
The first approach involves creating a string from random characters generated from another JavaScript function. The String.fromCharCode() function generates an ASCII character from a given number.
- Generate a random index within the range 0 to 61.
- If index<10, create a number character between 0 to 9.
- Else if index<36, generate a capital letter by adding 55.
- Else generate a small-case letter by adding 61.
function randomChar() {
var index = Math.floor(Math.random() * 62);
// Generate Number character
if (index < 10) {
return String(index);
// Generate capital letters
} else if (index < 36) {
return String.fromCharCode(index + 55);
} else {
// Generate small-case letters
return String.fromCharCode(index + 61);
}
}
function randomString(length) {
var result = "";
while (length > 0) {
result += randomChar();
length--;
}
return result;
}
2) Generate random strings with special characters
Generating a string by picking characters from a character list is a more direct approach. Additionally, it is easier to control all the characters which shall be allowed. Hence, the special characters can be introduced by similar including them in the character list.
- Initialize the value of declaration with a character list.
- Generate a random index between 0 to characterList.length.
- Append every character present in the index to the string.
const normalCharacters =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const specialCharacters = "@:;#&-?/%+*";
function randomString(length, isSpecial) {
var characterList = normalCharacters;
var result = "";
if (isSpecial) {
characterList += specialCharacters;
}
while (length > 0) {
// Pick random index from characterList
var index = Math.floor(Math.random() * characterList.length);
result += characterList[index];
length--;
}
return result;
}
3) Using built-in JavaScript functions
The Math.random() generates a decimal number between 0 and 1. The toString(36) operation converts the result into letters with base 32 representation. Finally, the first 2 letters consist of “0.” characters and are trimmed from the result.
function randomString() {
return Math.random()
.toString(36)
.slice(2);
}