Javascript: Some method to generate random chars


Method 1:

function randomchars1(type, len) {
    var radix = 10;
    switch (type) {
        case 3:
            radix = 36;
            break;
        case 2:
            radix = 16;
            break;
    }
    len = len || 40;
    var ar = new Uint8Array(len);
    window.crypto.getRandomValues(ar);
    var ret = [].map.call(ar, function (n) {
        return n.toString(radix);
    }).join("");
    ret = ret.slice(0, len)
    return ret;
}

Example 1: include 0-9

alert(randomchars1(1, 5));//44366

Example 2: include 0-9a-f

alert(randomchars1(2, 5));//f8a8a

Example 3: include 0-9a-z

alert(randomchars1(3, 5));//5s4p3

Method 2:

function randomchars2(type, len) {
    var s = "0123456789";
    switch (type) {
        case 3:
            s = "abcdefghijklmnopqrstuvwxyz0123456789";
            break;
        case 2:
            s = "abcdef0123456789";
            break;
        case 4:
            s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            break;
    }
    return Array(len).join().split(',').map(function () {
        return s.charAt(Math.floor(Math.random() * s.length));
    }).join('');
}

javascript-some-method-to-generate-random-chars

Example 1: include 0-9

alert(randomchars2(1, 5));//43366

Example 2: include 0-9a-f

alert(randomchars2(2, 5));//b8a8a

Example 3: include 0-9a-z

alert(randomchars2(3, 5));//514p3

Example 4: include 0-9a-zA-Z

alert(randomchars2(4, 5));//5A4p3

Leave a Reply