JavaScript中的随机字母数字字符串? [英] Random alpha-numeric string in JavaScript?

查看:94
本文介绍了JavaScript中的随机字母数字字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中生成随机字母数字(大写,小写和数字)字符串以用作可能唯一标识符的最短方式(在合理范围内)是什么?

What's the shortest way (within reason) to generate a random alpha-numeric (uppercase, lowercase, and numbers) string in JavaScript to use as a probably-unique identifier?

推荐答案

如果您只想允许特定字符,您也可以这样做:

If you only want to allow specific characters, you could also do it like this:

function randomString(length, chars) {
    var result = '';
    for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
    return result;
}
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');

这里有一个jsfiddle来演示: http://jsfiddle.net/wSQBx/

Here's a jsfiddle to demonstrate: http://jsfiddle.net/wSQBx/

另一种方法可以是使用一个特殊的字符串来告诉函数什么类型的要使用的字符。你可以这样做:

Another way to do it could be to use a special string that tells the function what types of characters to use. You could do that like this:

function randomString(length, chars) {
    var mask = '';
    if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
    if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    if (chars.indexOf('#') > -1) mask += '0123456789';
    if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\';
    var result = '';
    for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
    return result;
}

console.log(randomString(16, 'aA'));
console.log(randomString(32, '#aA'));
console.log(randomString(64, '#A!'));

小提琴: http://jsfiddle.net/wSQBx/2 /

或者,要使用如下所述的base36方法,您可以执行以下操作:

Alternatively, to use the base36 method as described below you could do something like this:

function randomString(length) {
    return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}

这篇关于JavaScript中的随机字母数字字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆