上代碼正則表達式
function regx(r,s){//驗證正則表達式是否對的方法
if (r == null || r == ""){
return false;
}
var patrn= new RegExp(r);
if (patrn.exec(s))
return true
return false
}
var codeLength = 6;//隨機數的長度(與正則表達式中的{6}相對應)
var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];//正則表達式的隨機數
var code = "/";//隨機數的前綴
var regxRule = "/[A-Za-z0-9]{6}";//須要驗證的正則
//循環獲取隨機數
for(let i = 0;i<codeLength;i++){
var charIndex = Math.floor(Math.random()*chars.length);
code+= chars [charIndex]
}
console.log(code);
//驗證生成的隨機數是否正確
regx(regxRule,code);
複製代碼