How to randomly generate alphanumeric strings in JavaScript

Last updated on Jun 30, 2021 by Suraj Sharma



In this tutorial, you will learn about generating random alphanumeric strings of length N in JavaScript.


Generate random strings using Math.random


Math.random() function is always helpful in generating random numbers. It returns a number in the range 0 to less than 1.

To generate random alphanumeric strings of length N, you can define a simple generateRandomString function, which takes string's length N as an argument as shown below.


Solution


function generateRandomString(n) {
    let randomString           = '';
    let characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    for ( let i = 0; i < n; i++ ) {
      randomString += characters.charAt(Math.floor(Math.random()*characters.length));
   }
   return randomString;
}

generateRandomString(6) // "ersNAI"


Another way to generate random strings is to convert the random numbers returned from the Math.random() function to base 36 numbers by calling the toString(36) function on the random numbers.


Solution


let randomString = Math.random().toString(36).substr(2, 5)

randomString // "4vl3g"


Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.