标签归档:字符串

使用 JavaScript 生成随机字符串

用途:如 Oauth 认证等需要的等长随机字符串。

/**
 * By James from http://www.xinotes.org/notes/note/515/
 */
function randomString(length) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');

    if (! length) {
        length = Math.floor(Math.random() * chars.length);
    }

    var str = '';
    for (var i = 0; i < length; i++) {
        str += chars[Math.floor(Math.random() * chars.length)];
    }
    return str;
}

/* examples */

// generate a random string of random length
randomString();

// generate a random string of length 8
randomString(8);