且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在javascript中生成安全密码

更新时间:2021-12-01 14:58:48

这里有一些有用的字符串函数:

Here are some useful String functions:

String.prototype.pick = function(min, max) {
    var n, chars = '';

    if (typeof max === 'undefined') {
        n = min;
    } else {
        n = min + Math.floor(Math.random() * (max - min + 1));
    }

    for (var i = 0; i < n; i++) {
        chars += this.charAt(Math.floor(Math.random() * this.length));
    }

    return chars;
};


// Credit to @Christoph: http://***.com/a/962890/464744
String.prototype.shuffle = function() {
    var array = this.split('');
    var tmp, current, top = array.length;

    if (top) while (--top) {
        current = Math.floor(Math.random() * (top + 1));
        tmp = array[current];
        array[current] = array[top];
        array[top] = tmp;
    }

    return array.join('');
};

您的密码如下所示:

var specials = '!@#$%^&*()_+{}:"<>?\|[];\',./`~';
var lowercase = 'abcdefghijklmnopqrstuvwxyz';
var uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var numbers = '0123456789';

var all = specials + lowercase + uppercase + numbers;

var password = '';
password += specials.pick(1);
password += lowercase.pick(1);
password += uppercase.pick(1);
password += all.pick(3, 10);
password = password.shuffle();

演示: http: //jsfiddle.net/Blender/ERCsD/6/

Demo: http://jsfiddle.net/Blender/ERCsD/6/