This page looks best with JavaScript enabled

Generate Random Strings in Javascript

 ·   ·  ☕ 1 min read

Generate random strings in multiple ways in Javascript.

Use crypto

The quickest and easiest way to generate random strings.

1
2
3
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.

1
2
3
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.

1
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.

    1
    2
    
    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/]
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things