本文介绍了在javascript中生成具有要求的随机密码字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想生成一个随机字符串,它必须包含 5 个 a-z 字母和 3 个数字.
I want to generate a random string that has to have 5 letters from a-z and 3 numbers.
如何使用 JavaScript 执行此操作?
How can I do this with JavaScript?
我有以下脚本,但它不符合我的要求.
I've got the following script, but it doesn't meet my requirements.
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var string_length = 8;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
推荐答案
强制使用固定数量的字符是一个糟糕的想法.它不会提高密码的质量.更糟糕的是,它减少了可能的密码数量,因此通过暴力破解的黑客攻击变得更加容易.
Forcing a fixed number of characters is a bad idea. It doesn't improve the quality of the password. Worse, it reduces the number of possible passwords, so that hacking by bruteforcing becomes easier.
要生成由字母数字字符组成的随机单词,请使用:
To generate a random word consisting of alphanumeric characters, use:
var randomstring = Math.random().toString(36).slice(-8);
它是如何工作的?
Math.random() // Generate random number, eg: 0.123456
.toString(36) // Convert to base-36 : "0.4fzyo82mvyr"
.slice(-8);// Cut off last 8 characters : "yo82mvyr"
Number.prototype 的文档.toString
和 string.prototype.slice
方法.
这篇关于在javascript中生成具有要求的随机密码字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!