Generate random strings in multiple ways in Javascript.
Use crypto
The quickest and easiest way to generate random strings.
const crypto = require("crypto");
var txt = crypto.randomBytes(10).toString("hex");
console.log("txt: ", txt); // a3f4ac84da8da6bf172b
Crypto library is available in node. On the client side, use window.crypto.
Use random
Use Math.random() to generate a string of random set of characters and numbers.
let a = Math.random().toString(36).substring(2, 15);
console.log(a); // yzcjf8welj
The above code converts a random number to to its base-36 form (toString(36)) and outputs the string after removing the prefix.
Use faker
Faker libraries (here’s a popular one) help you not only to generate random strings, but random anything.
You can locally install the library and start cranking up randoms.
var randomName = faker.name.findName();
Other
Use the hosted service for faker libraries. Note that these are hosted on servers that do not support large number of concurrent connections and may throw errors.
curl http://faker.hook.io?property=name.findName
- If you are looking at generating data quickly and do not care about reuse, you can look at online generators like [https://www.generatedata.com/]