Generates a random string of characters for the specific number of bits - Node.js String

Node.js examples for String:Char

Description

Generates a random string of characters for the specific number of bits

Demo Code

/**// w w w.  j a va  2  s.  c o m
 * Generates a random string of characters for the specific number of bits
 *
 * @method randomString
 * @param {int} bits number of bits to use
 * @return {string} A random string of characters
 */
exports.randomString = function (bits) {
    var chars, rand, i, ret
    chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    ret = ''

    // in v8, Math.random() yields 32 pseudo-random bits (in spidermonkey it gives 53)
    while (bits > 0) {
        rand = Math.floor(Math.random() * 0x100000000) // 32-bit integer
        // base 64 means 6 bits per character, so we use the top 30 bits from rand to give 30/6=5 characters.
        for (i = 26; i > 0 && bits > 0; i -= 6, bits -= 6) ret += chars[0x3F & rand >>> i]
    }

    return ret;
};

Related Tutorials