需要產生驗證碼、隨機佔位字、測試資料時,隨機字母是最基礎的一塊。做法是把「a 的字元碼」當作起點,加上 0 到 25 的隨機位移。
/**
* 回傳一個隨機字母
* @param {string} flag "lower" 小寫、"upper" 大寫
*/
function getCharacter(flag) {
var character = "";
if (flag === "lower") {
character = String.fromCharCode(
Math.floor(Math.random() * 26) + "a".charCodeAt(0)
);
}
if (flag === "upper") {
character = String.fromCharCode(
Math.floor(Math.random() * 26) + "A".charCodeAt(0)
);
}
return character;
}
/** 隨機小寫字母 */
function getLowerCharacter() {
return getCharacter("lower");
}
/** 隨機大寫字母 */
function getUpperCharacter() {
return getCharacter("upper");
}
"a".charCodeAt(0) 得到 97,"A" 是 65。Math.random() 回傳 0 到 1 之間(不含 1)的小數,乘上 26 後取 floor,得到 0 到 25 的整數,加上起點就落在 a–z 或 A–Z 的連續區間,最後用 String.fromCharCode 轉回字元。
小寫與大寫的碼位剛好相差 32,所以也能簡化成先取小寫再決定是否轉大寫:
function randomLetter(upper) {
var ch = String.fromCharCode(97 + Math.floor(Math.random() * 26));
return upper ? ch.toUpperCase() : ch;
}
function randomLetters(len, upper) {
var s = "";
for (var i = 0; i < len; i++) { s += randomLetter(upper); }
return s;
}
// 大小寫混合
function randomMixed(len) {
var pool = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var s = "";
for (var i = 0; i < len; i++) {
s += pool.charAt(Math.floor(Math.random() * pool.length));
}
return s;
}
用「字元池 + 隨機索引」的寫法更好擴充:要加上數字或符號只要改 pool 字串,不必再寫分支判斷。
Math.random() 不是密碼學安全的亂數,它的內部狀態可被推導。若這些字是用在一次性驗證碼、重設密碼的權杖、Session ID 這類場合,請改用 window.crypto.getRandomValues()(或 Node 的 crypto.randomBytes)來取亂數,並把結果寫在伺服器端驗證、加上有效期限與嘗試次數限制。用於畫面上的佔位文字或測試資料,Math.random() 則完全夠用。