Friday, September 5, 2025
HomeLanguagesJavascriptGenerate random alpha-numeric string in JavaScript

Generate random alpha-numeric string in JavaScript

In this article with the help of javascript  we are generating the alpha-numeric string of specific length using javascript, here are some common method 

Approach 1:

  • Creates a function that takes 2 arguments one is the length of the string that we want to generate and another is the characters that we want to be present in the string.
  • Declare new variable ans = ‘ ‘.
  • Traverse the string in reverse order using for loop.
  • Use JavaScript Math.random() method to generate the random index and multiple with the length of the string.
  • Use JavaScript Math.floor( ) to round off it and add it into the ans.

Example 1: This example uses the Math.random() method to generate the random index and then appends the character from the string we passed. 

Javascript




function randomStr(len, arr) {
    let ans = '';
    for (let i = len; i > 0; i--) {
        ans +=
            arr[(Math.floor(Math.random() * arr.length))];
    }
    console.log(ans);
}
 
randomStr(20, '12345abcde');


Output

eecedee32d5245ba5ee3

Approach 2:

  • First, generate a random number using Math.random() method.
  • Use JavaScript toString(36) to convert it into base 36 (26 char + 0 to 9) which is also an alpha-numeric string.
  • Use JavaScript String.slice() method to get the part of the string which is started from position 2.

Example 2: This example first generates a random number(0-1) and then converts it to base 36 which is also an alpha-numeric string by using toString(36)() method

Javascript




function GFG_Fun() {
    console.log(
        Math.random().toString(36).slice(2));
}
GFG_Fun()


Output

vv1lcnuwtm
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11863 POSTS0 COMMENTS
Shaida Kate Naidoo
6750 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6701 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS