nodejs create random string code example

Example 1: javascript generate random string

// Generate a random alphanumerical string of length 11 ( change substring parameter for other length)
Math.random().toString(36).substring(2);

Example 2: javascript get random string

function getRandomString(length) {
    var randomChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var result = '';
    for ( var i = 0; i < length; i++ ) {
        result += randomChars.charAt(Math.floor(Math.random() * randomChars.length));
    }
    return result;
}

//usage: getRandomString(20); // pass desired length of random string

Example 3: node random string

var crypto = require("crypto");
var id = crypto.randomBytes(20).toString('hex');

// "bb5dc8842ca31d4603d6aa11448d1654"

Tags:

Php Example