Gark Garcia
Gark Garcia

Reputation: 460

What are the best approches for generating random strings from a set of allowed characters?

I have a very simple javascript program which involves generating random strings of characters from a given set of allowed characters.

Generating random strings from a regular expression with randexp.js seems to be the most appropriate way to do so. However, since the set of allowed characters is a very simple one (basically all uppercase characters from the English alphabet and all digits) I wonder if loading an entire library isn't a bit overkill for such purpose. Instead I'm doing something like the following:

const chars = ["A", "B", "C", "D", ...];

let random = () => { return chars[Math.floor(Math.random() * chars.length)] };

Is there something really bad about this (besides being a bit bulky and awkward) or is this ok in this specific case? What would the best approach for generating random string from a set of allowed characters be?

Upvotes: 0

Views: 130

Answers (1)

wp78de
wp78de

Reputation: 18980

This is arguably a great use case for randexp.js (GitHub), a JavaScript library that generates random strings based on regex patterns. It is very powerful and can be used for all sorts of things.

let randexp = new RandExp(/[A-D]{1,5}/);
for(i=0;i<3;i++)
    console.log(randexp .gen());

//random numbers
console.log(new RandExp(/[1-6]/).gen());
//words with optional parts
console.log(new RandExp(/great|good( job)?|excellent/).gen());
//wildcard gen: eg. keys
console.log(new RandExp(/random stuff: .{8,20}/).gen());
<script src="https://github.com/fent/randexp.js/releases/download/v0.4.3/randexp.min.js"></script>

Usually, get it via npm or download a release version.

Upvotes: 1

Related Questions