/

Generating Random and Unique Strings in JavaScript

Generating Random and Unique Strings in JavaScript

How to Create an Array of 5000 Unique Strings in JavaScript

While working on my online course platform, I faced the challenge of generating thousands of unique URLs. Each person taking the course needed to be assigned a unique URL, which would be associated with their purchase email. By having a separate URL for each person, I could eliminate the need for a login system and prevent abuse if a URL was unintentionally or intentionally shared with the public.

To tackle this problem, I wrote a Node.js script using the randomstring package. Here’s how I did it:

  1. First, I created a generateStrings() function that takes two parameters: numberOfStrings and stringLength.
1
2
3
4
5
6
7
8
9
10
const generateStrings = (numberOfStrings, stringLength) => {
const randomstring = require('randomstring');
const set = new Set();

while (set.size < numberOfStrings) {
set.add(randomstring.generate(stringLength));
}

return set;
}

This function uses the randomstring package to generate random strings of the specified length. The strings are added to a Set object, ensuring that duplicates are automatically discarded.

  1. To generate the desired number of unique strings, simply call the generateStrings() function and provide the desired values for numberOfStrings and stringLength. For example:
1
const strings = generateStrings(100, 20);

In this case, we are generating 100 unique strings, each with a length of 20 characters.

  1. Once we have the set of unique strings, we can iterate over them using the values() method of the Set object:
1
2
3
for (const value of strings.values()) {
console.log(value);
}

By iterating over the set, we can access and use the generated unique strings in any way we want.

By following these steps, we can easily generate random and unique strings in JavaScript for various use cases like generating unique URLs, tokens, or identifiers.

Tags: JavaScript, random strings, unique strings, Node.js, string generation