簡體   English   中英

生成帶有大寫字母和數字且不帶O和0的隨機字符串

[英]Generate random string with capital letters and numbers without O and 0

我想生成一個隨機字符串,長度為12,僅包含大寫字母,數字不包含字母O或javascript中的數字0。 這是我所擁有的:

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

但是問題是,它不是全部大寫,而且我不希望字母O或數字0。謝謝

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();

這是一個快速的解決方案,可能不是最佳選擇。

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']));

編輯:此解決方案允許輸出長度和要排除的字符作為參數傳遞。

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()

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的字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM