- How to Generate Random String In JavaScript
- Why do we need random strings?
- Ways to generate random strings in JavaScript
- 1. Create a Custom method to generate random string
- 4 Ways to Generate Random Strings in JavaScript
- Using Math.random() and charAt()
- Using window.crypto.getRandomValues()
- Using Math.floor(Math.random() * Date.now())
- Using a third-party package
- 6174 / Random-string
- How to generate a random string in JavaScript
- You might also like.
How to Generate Random String In JavaScript
Random strings are used for various purposes in software development. For example, they can be used to code user IDs, generate passwords, and construct tokens in applications. If you’re developing a JavaScript-based program that needs random strings — or any other type of pseudo-random data — then this article is for you! You see, generating random characters (or strings) is easy with the right tools and techniques. Luckily, this article covers exactly that. Let’s get started…
Why do we need random strings?
Random strings are used to construct tokens, user IDs, and passwords in software. Let’s say you want to build a login system for a web application. You need to assign each user a unique login ID to allow them to log in. You can create a random string of characters to act as the user ID. The same applies to user tokens, which are used by various systems. Random strings are also useful for generating sales. Salt is a random string that’s used to add additional security to login systems. It makes it harder for hackers to brute force or log in to your system as they have to guess a unique salt for each user.
Ways to generate random strings in JavaScript
This section discusses four methods that allow you to generate a random string in JavaScript.
- Create a Custom method to generate random string.
- Using Math.random() method to generate random string.
- Using crypto.getRandomValues() method to generate random string.
- Using URNG library to generate random string – Let’s discuss each method in detail.
1. Create a Custom method to generate random string
You can create a custom method to generate a random string. Here we defined the words, numbers, and special characters. You can call this javascript function any time to generate a random string
4 Ways to Generate Random Strings in JavaScript
When developing web projects (either front-end or back-end), random strings are commonly used for various purposes, such as making unique identifiers for user accounts or objects in a database or creating random file names to avoid naming conflicts. This practical, example-based article will walk you through a couple of different ways to generate a random string in JavaScript.
Using Math.random() and charAt()
We can use the Math.random() function (that is available on both the browser environment and Node.js environment by default) to generate a random string of the specified length. It helps us randomly select characters from the character’s string (that includes all letters and numbers) by using the charAt() function.
const generateRandomString = (length) => < let result = ''; const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const charactersLength = characters.length; for (let i = 0; i < length; i++) < result += characters.charAt(Math.floor(Math.random() * charactersLength)); >return result; >; console.log(generateRandomString(5)); console.log(generateRandomString(30));
The output (that will change each time you execute the code):
G4vcg script.js:13 md2pNVDvOspbyycygm8B0g4kjYqv0e
Using window.crypto.getRandomValues()
This approach is quite similar to the previous one, but there is a key differentiating point is that we will use the window.crypto.getRandomValues() function instead of the Math.random() function.
const generateRandomString = (length) => < const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const charactersLength = characters.length; let result = ''; // Create an array of 32-bit unsigned integers const randomValues = new Uint32Array(length); // Generate random values window.crypto.getRandomValues(randomValues); randomValues.forEach((value) =>< result += characters.charAt(value % charactersLength); >); return result; > console.log(generateRandomString(10)); console.log(generateRandomString(25));
jLogAh04m8 script.js:15 CcJRRcojGbsVWETXBVG5rBpch
Using Math.floor(Math.random() * Date.now())
We can create a random string by multiplying a random number with the current timestamp and then converting it to a base-36 string using the toString() function.
const generateRandomString = () => < return Math.floor(Math.random() * Date.now()).toString(36); >; console.log(generateRandomString());
This approach is quick and simple, but we cannot control the length of the output.
Using a third-party package
There is a plethora of open-source packages that provide functionalities to help you produce random strings. One of the most popular is uuid.
You can install it to your project by running the following command:
import < v4 as uuidv4 >from 'uuid'; const randomString1 = uuidv4(); const randomString2 = uuidv4(); console.log(randomString1); console.log(randomString2);
b8d03ea8-db49-4afb-8b09-5727b1ea4b10 76adaeb0-5129-4c84-9984-ccd7b0f0927b
The v4 function generates a random version 4 UUID (UUID stands for Universally Unique Identifier).
6174 / Random-string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
//http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript |
Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); |
Here’s a little different spin.
- Sets are attached to function (rnd.num, rnd,alphaLower, etc.)
- Sequential sets are generated using fromCharCode
- Uses generator function
- Uses rest params for sets — ie rnd([length], [set1], [set2], . )
const rnd = (() => const gen = (min, max) => max++ && [. Array(max-min)].map((s, i) => String.fromCharCode(min+i)); const sets = num: gen(48,57), alphaLower: gen(97,122), alphaUpper: gen(65,90), special: [. `~!@#$%^&*()_+-=[]\<>|;:'",./<>?`] >; function* iter(len, set) if (set.length 1) set = Object.values(sets).flat(); for (let i = 0; i len; i++) yield set[Math.random() * set.length|0] > return Object.assign(((len, . set) => [. iter(len, set.flat())].join('')), sets); >)(); console.log('OUTPUT: ', rnd(20)); // Use all sets // OUTPUT: Kr8K1,f5hQa;YJC~7K9z console.log('OUTPUT: ', rnd(20, rnd.alphaLower)); // OUTPUT: cpjbkwvslxsofzvkekcw console.log('OUTPUT: ', rnd(20, rnd.alphaUpper rnd.special)); // OUTPUT: S]|-X]=N>TZC,GE;=,.D
keep in mind that Math.random can also return 0 and that some conversions using .toString(n) might be much shorter that the number of chars you expect according to the second argument of substr / substring : https://jsfiddle.net/karfau/5632zu84/27/
just for the lulz i made this:
const random = (function() const buffer = new Uint8Array(32); let index; let bitIndex; const max = BigInt(buffer.length); const reset = function() index = 0n; bitIndex = 0n; crypto.getRandomValues(buffer); >; reset(); const getBits = function(count) let bits = 0n; while (count > 0n) const todo = count 8n - bitIndex ? count : 8n - bitIndex; count -= todo; bits = bits <todo; bits += (BigInt(buffer[index]) >> bitIndex) & ((1n <todo) -1n); bitIndex += todo; if (bitIndex === 8n) bitIndex = 0n; index++; > if (index === max) reset(); > > return bits; >; const countBits = function(num) let bitCount = 0n; while (num > 0n) bitCount++; num = num >> 1n; > return bitCount; >; const getN = function(max, bitCount) if (max 0n) throw new Error("this does not compute unless you want an infinite loop"); > let out; do out = getBits(bitCount); > while (out >= max); return out; >; return function(input, count) let wasNumber = false; let wasString = false; switch (typeof input) default: throw new Error("unsupported input"); > case "number": wasNumber = true; input = BigInt(input); > case "bigint": const out = getN(input, countBits(max)); return wasNumber ? Number(out) : out; > case "string": wasString = true; input = input.split(""); > case "object": if (!Array.isArray(input)) throw new Error("objects are not supported here"); > if (typeof count != "number" && typeof count != "bigint") throw new Error("you need to specify a count"); > const contentCount = BigInt(input.length); const bitCount = countBits(contentCount); const out = [. Array(count)].map(_=> return input[getN(contentCount, bitCount)]; >); return wasString ? out.join("") : out; > > >; >)();
random(«such String», 20); would return a string with 20 characters randomly made out of the given input string.
like: «r gsuhuSrtrguintughc»
random(«10», 20) would generate random bits as string: «10011001011000111010»
if you provide an array, it will also return an array:
random(«The quick brown Fox jumps over the lazy Dog».split(» «), 5);
returns something like:
[«over»,»The»,»Dog»,»Fox»,»over»]
now the mindblow.. when using an array, the type of the content is interchangable. you can use objects, numbers, what ever you like.
now.. how to random sort an array with this you may ask..
const randomSort = function(array) const tmp = []; while(array.length > 0) tmp.push(array.splice(random(array.length), 1)[0]); array.push(. tmp); return array; >; >; const array = ["foo", "bar", "asdfg", "rofl", "lol"]; randomSort(array); console.dir(array); // something like: ["asdfg","bar","lol","rofl","foo"]
i was a bit too lazy to write a class for this.
also const buffer = new Uint8Array(32); could be reduced to const buffer = new Uint8Array(1); but i GUESS calling crypto.getRandomValues will in itself cause a performance penalty while buffering a little bit for the future is probably slightly faster.
just a guess though. i did not benchmark this.
also sorry for not providing comments here. i just made this code out of the blue. simple braingasm.
while using Math.pow and Math.min i was getting «bigint cannot be converted to number» issues thus i just wrote them with ternary.
keep in mind, the buffer usage will differ each run.
it is throwing out bit sequences that were exceeding the amount of items inside the input data.
also sadly there is no log2 in javascripts native bigint yet so i cannot count bits efficiently.
oh and @MelodicCrypter you might like this 😀
How to generate a random string in JavaScript
There are many ways available to generate a random string in JavaScript. The quickest way is to use the Math.random() method.
The Math.random() method returns a random number between 0 (inclusive), and 1 (exclusive). You can convert this random number to a string and then remove the trailing zeros:
const rand = Math.random().toString().substr(2, 8); // 60502138
The above code will generate a random string of 8 characters that will contain numbers only.
To generate an alpha-numeric string, you can pass an integer value between 2 and 36 to the toString() method called radix . It defines the base to use for representing a numeric value.
For a binary string (0-1), you can pass 2 as radix to toString() :
const binary = Math.random().toString(2).substr(2, 8); // 01100110
To generate a fully random string, you should pass 16 or greater as a radix value to toString() :
const rand = Math.random().toString(16).substr(2, 8); // 6de5ccda
Let us write a function by using the above code to generate a random string anywhere between 0 and 14 characters:
const random = (length = 8) => return Math.random().toString(16).substr(2, length); >; console.log(random()); // bb325d9f console.log(random(6)); // e51d83 console.log(random(10)); // e84c416cc7 console.log(random(14)); // ee16dfc68e361
To generate large random strings (14+ characters long), you have to write your own generator. The following example demonstrates how you can generate strings of any size by picking characters randomly from A-Z , a-z , and 0-9 :
const random = (length = 8) => // Declare all characters let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; // Pick characers randomly let str = ''; for (let i = 0; i length; i++) str += chars.charAt(Math.floor(Math.random() * chars.length)); > return str; >; console.log(random()); // JgKGQEUx console.log(random(12)); // ttwbeshkYzaX console.log(random(20)); // zZN7uH9pPjhJf30QNus5
In the above example, Math.random() and Math.floor() methods are used to generate a random index of the character in the specified characters (A-Z a-z 0-9). The for loop is used to loop through the number passed into the random() function. During each iteration of the loop, a random character is selected from the characters’ list. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.