Javascript Random String Function

2013-04-18 13:47:41

/**
 * Generates a string of random characters of a specified length
 *
 * @param len length of the resulting string. Default is 10 if unspecified
 * @returns {string}
 */
function randString(len) {
    len = len || 10;
    var s = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$',
        out = '',
        randomIndex;
    for(var i=0; i < len; i++) {
        randomIndex = Math.round(Math.random()*(s.length-1));
        out += s.substring(randomIndex, randomIndex+1)
    }
    return out
}