Generate random string in JavaScript.
1 min readDec 26, 2020
The other day I had a challenge and I have to create a function that generates the random string.
I’d like to show a couple of different ways to do that.
1. User the npm library to generate a random string:
To install randomstring, use npm:
npm install randomstring
Usage
var randomstring = require("randomstring");
randomstring.generate();// >> "XwPp9xazJ0ku5CZnlmgAx2Dld8SHkAeT"randomstring.generate(7);// >> "xqm5wXX"
randomstring.generate({length: 12,charset: 'alphabetic'});// >> "AqoTIzKurxJi"
randomstring.generate({charset: 'abc'});// >> "accbaabbbbcccbccccaacacbbcbbcbbc"
Command Line Usage
$ npm install -g randomstring$ randomstring
> sKCx49VgtHZ59bJOTLcU0Gr06ogUnDJi$ randomstring 7
> CpMg433$ randomstring length=24 charset=github readable
> hthbtgiguihgbuttuutubugg
2. Create a function. The function I used:
let refCode = Math.random().toString(20).substring(2, 5) + Math.random().toString(20).substring(2, 5);refCode;
// >> f1i64a
3. Using MD5 Library:
Usage
Install the blueimp-md5 package with npm:
npm install blueimp-md5
Include the (minified) JavaScript MD5 script in your HTML markup:
<script src="js/md5.min.js"></script>
In your application code, calculate the (hex-encoded) MD5 hash of a string by calling the md5 method with the string as an argument:
var hash = md5('value') // "2063c1608d6e0baf80249c42e2be5804"
The shortest way:
md5(Math.random())
To limit the size to 5:
md5(Math.random()).substr(0, 5)
Have fun coding!