How to Generate a random String/Letter in JavaScript

In this article, we will create JavaScript functions to accomplish the following functionalities:

  1. Generate a random letter from the ASCII characters.
  2. Generate a random string of a given length.
  3. Generate random strings with special characters.
random_string_console
Generating random strings in the console

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.

  1. Generate a random index within the range 0 to 61.
  2. If index<10, create a number character between 0 to 9.
  3. Else if index<36, generate a capital letter by adding 55.
  4. 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.

  1. Initialize the value of declaration with a character list.
  2. Generate a random index between 0 to characterList.length.
  3. 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);
}