从一组允许的字符生成随机字符串的最佳方法是什么?

时间:2021-10-29 22:32:18

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

我有一个非常简单的javascript程序,它涉及从给定的一组允许字符生成随机字符串。

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:

使用randexp.js从正则表达式生成随机字符串似乎是最合适的方法。但是,由于允许的字符集非常简单(基本上都是英文字母和所有数字中的大写字符),我想知道加载整个库对于这样的目的来说是不是有点过分。相反,我正在做类似以下的事情:

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?

这有什么不好的事情(除了有点笨重和笨拙)还是在这种特殊情况下还可以吗?从一组允许的字符生成随机字符串的最佳方法是什么?

1 个解决方案

#1


1  

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.

这可以说是randexp.js(GitHub)的一个很好的用例,它是一个基于正则表达式模式生成随机字符串的JavaScript库。它非常强大,可以用于各种各样的事情。

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.

通常,通过npm获取它或下载发布版本。

#1


1  

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.

这可以说是randexp.js(GitHub)的一个很好的用例,它是一个基于正则表达式模式生成随机字符串的JavaScript库。它非常强大,可以用于各种各样的事情。

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.

通常,通过npm获取它或下载发布版本。