How to generate random string without repetition in Node.js

1 Answer

0 votes
function generateUniqueRandomString(total) {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    const chars_length = chars.length
    let result = '';
    let usedChars = new Set();

    while (result.length < total) {
        const randomIndex = Math.floor(Math.random() * chars_length);
        const randomChar = chars[randomIndex];

        if (!usedChars.has(randomChar)) {
            result += randomChar;
            usedChars.add(randomChar);
        }
    }

    return result;
}

console.log(generateUniqueRandomString(14)); 

 
 
/*
 
run:
 
ZG5Bq7o0gpInz3
 
*/
  

 



answered Nov 4, 2024 by avibootz

Related questions

1 answer 110 views
1 answer 115 views
1 answer 106 views
1 answer 110 views
...