Open In App

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:



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




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:

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




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

Output
vv1lcnuwtm
Article Tags :