我想从正则表达式中生成一个随机字符串。
例子:
random_string(/^[0-9]{4}$/) //==> 7895
random_string(/^[0-9]{4}$/) //==> 0804
random_string(/^[0-9,A-Z]{4}$/) //==> 9ZE5
random_string(/^[0-9,A-Z]{4}$/) //==> 84D6
最佳答案
可以看randexp.js ,它正是你想要的
console.log(new RandExp(/^[0-9]{4}$/).gen());
console.log(new RandExp(/^[0-9]{4}$/).gen());
console.log(new RandExp(/^[0-9,A-Z]{4}$/).gen());
console.log(new RandExp(/^[0-9,A-Z]{4}$/).gen());
<script src="https://github.com/fent/randexp.js/releases/download/v0.4.3/randexp.min.js"></script>
当然也有一些限制:
Repetitional tokens such as *, +, and {3,} have an infinite max range. In this case, randexp looks at its min and adds 100 to it to get a useable max value. If you want to use another int other than 100 you can change the max property in RandExp.prototype or the RandExp instance.
关于javascript - 如何从正则表达式创建随机字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43547777/