实用的 JavaScript 方法
- 工具类
- 获取浏览器 Cookie
- 获取 Url 参数
- 格式化时间对象
- 生成一个 UUID
- 生成一个随机整数
- 生成一个随机验证码
- 验证类
工具类
获取浏览器 Cookie
function getCookie(name) {
var cookieList = document.cookie.split("; ");
var cookieJson = {};
for (var index in cookieList) {
cookieJson[cookieList[index].split("=")[0]] = cookieList[index].split("=")[1];
}
return cookieJson[name]
}
获取 Url 参数
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return (false);
}
格式化时间对象
function dateFormat(fmt, date) {
var ret;
const opt = {
"y+": date.getFullYear().toString(),
"M+": (date.getMonth() + 1).toString(),
"d+": date.getDate().toString(),
"h+": date.getHours().toString(),
"m+": date.getMinutes().toString(),
"s+": date.getSeconds().toString()
};
for (var k in opt) {
ret = new RegExp("(" + k + ")").exec(fmt);
if (ret) {
fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
};
};
return fmt;
}
生成一个 UUID
function createUUID() {
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}
生成一个随机整数
function createRandom(n, m) {
n = Number(n);
m = Number(m);
if (n > m) {
var temp = n;
n = m;
m = temp;
}
return Math.floor(Math.random() * (m - n) + n);
}
生成一个随机验证码
function createCode(len) {
var codeStr = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
var str = '';
var getRandom = function(n, m) {
n = Number(n);
m = Number(m);
if (n > m) {
var temp = n;
n = m;
m = temp;
}
return Math.floor(Math.random() * (m - n) + n);
}
for (var i = 0; i < len; i++) {
var ran = getRandom(0, codeStr.length);
str += codeStr.charAt(ran);
}
return str
}
验证类
验证邮箱
function validateMail(mail) {
var strRegex = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
if (strRegex.test(mail)) {
return true;
} else {
return false;
}
}
验证手机号码
function validatePhone(phone) {
var phoneReg = /^1[3-578]\d{9}$/;
if (phoneReg.test(phone)) {
return true;
} else {
return false;
}
}
验证身份证号码
function validateIdCard(idCode) {
var weight_factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
var check_code = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
var code = idCode + "";
var last = idCode[17];
var seventeen = code.substring(0, 17);
var arr = seventeen.split("");
var len = arr.length;
var num = 0;
for (var i = 0; i < len; i++) {
num = num + arr[i] * weight_factor[i];
}
var resisue = num % 11;
var last_no = check_code[resisue];
var idcard_patter =
/^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/;
var format = idcard_patter.test(idCode);
return last === last_no && format ? true : false;
}