使用大写字母和数字生成随机字符串,不带O和0

时间:2017-01-20 17:32:24

标签: javascript string random

我想生成一个长度为12的随机字符串,只有大写字母,数字没有字母O或数字0在javascript中。这就是我所拥有的:

Math.random().toString(36).substr(2, 12)

但问题是它不是全部资本而且我不想要字母O或数字0.谢谢

4 个答案:

答案 0 :(得分:2)

function rand_str_without_O0() {
    const list = "ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
    var res = "";
    for(var i = 0; i < 12; i++) {
        var rnd = Math.floor(Math.random() * list.length);
        res = res + list.charAt(rnd);
    }
    return res;
}

用法:

var randomString = rand_str_without_O0();

答案 1 :(得分:1)

这是一个快速解决方案,可能不是最佳解决方案。

var myString = function(len, excluded) {
  var included = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

  // remove the excluded chars from the included string
  for (var i = 0; i < excluded.length; i++) {
    included = included.split(excluded[i]).join('');
  }

  // add len random chars form whatever is left.
  var output = '';
  for (var i = 0; i < len; i++) {
    output += included.charAt(Math.random() * included.length);
  }

  return output;
}

您可以使用所需的长度和要排除的字符数组来调用它:

console.log(myString(12, ['0', 'O']));

编辑:此解决方案允许排除输出长度和字符作为参数传递。

答案 2 :(得分:0)

var all_chars_without_O0 = 'ABCDEFGHIJKLMNPQRSTUVWXYZ123456789'.split('');

// Returns a random integer between min (included) and max (excluded)
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

function pickRandom(arr) {
  return arr[getRandomInt(0, arr.length)];
}

function randomString(length = 12, chars = all_chars_without_O0) {
  var s = '';
  while (length--)
    s += pickRandom(chars);
  return s;
}

https://jsfiddle.net/MrQubo/fusb1746/1/

或者使用lodash:

var all_chars_without_O0 = 'ABCDEFGHIJKLMNPQRSTUVWXYZ123456789'.split('');

function randomString(length = 12, chars = all_chars_without_O0) {
  return _.sampleSize(chars, length).join('');
}

但是,您应该收到警告,Math.random()并未提供加密安全随机数。有关详细信息,请参阅Math.random()

答案 3 :(得分:0)

let foo = function(length) { //length should be <= 7
  return  Math.random().toString(36).toUpperCase().replace(/[0-9O]/g, '').substring(1,length+1)
}

response = foo(6) + foo(6)

这将首先生成随机字符串,并将其转换为大写,然后删除不需要的值,然后创建所需长度的子字符串。据我所知,这将生成至少7个字符的字符串,因此您可以使用它两次以生成长度为12的字符串。