Last updated: Jul 26, 2022

Generate a nanoid with 24 random characters using JavaScript

To generate a random string in JavaScript, we first define a variable with name result and set its default value to an empty string.

Second, we define a new variable with name chars that holds all the english alphabets (both lowercase and uppercase) and numbers from 0 to 9.

Third, we loop over the value of chars variable and use the concatenation and assignment operator to randomly select and store 24 characters in the result variable.

function nanoid() {
    var result = '';
    var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    for (let i = 0; i < 24; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
  }

You can generate a string of any length by changing the value of temporary variable i in our for loop. Also, a more secure nanoid can be generated by either adding a prefix or including special characters in the string.