Generate random and unique strings in JavaScript

How to create an array of 5000 unique strings in JavaScript

When building a platform for online courses, I ran into the problem of generating thousands of unique URLs.

Everyone who takes the course will be assigned a unique URL. The backend knows all these URLs and maps valid URLs to course content.

I want a unique URL because I can associate the URL with the purchase email.

This way, I can avoid logging in, and using a separate URL for everyone can prevent eventual abuse if the URL is unintentionally or deliberately shared among the public.

Therefore, I set out to write my Node.js script.

I usedRandom stringPackage and then I add the number toSet objectUntil I get the phone number I want. Using Set means that each string is unique, because the calladdAnd passing the repeated string will perform any operation silently.

I made onegenerateStrings()Functions that return collections:

const generateStrings = (numberOfStrings, stringLength) => {
  const randomstring = require('randomstring')
  const s = new Set()

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

return s }

I Can Use

const strings = generateStrings(100, 20)

Where 100 is the number of strings I want, and 20 is the length of each string.

After getting the settings, we can usevalues()Setting method:

for (const value of strings.values()) {
  console.log(value)
}

Download mine for freeJavaScript beginner's manual


More js tutorials: