1. 截取地址栏里携带的参数
export function getQueryString(url, name) {
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
let r = ("?" + url.split("?")[1]).substr(1).match(reg);
if (r != null) return unescape(r[2]);
return null;
}
2.时间转换工具
export function formatDate(timestamp) {
if (!timestamp) {
return "";
}
let date = new Date(timestamp);
let month = date.getMonth() + 1;
let strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
let dateStr = date.getFullYear() + "-" + month + "-" + strDate;
return dateStr;
}
export function formatTime(timestamp) {
if (!timestamp) {
return "";
}
let date = new Date(timestamp);
let year = date.getFullYear();
let month = date.getMonth() + 1;
if (month >= 1 && month <= 9) {
month = "0" + month;
}
let strDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
let min =
date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
let sec =
date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
let dateStr =
year + "-" + month + "-" + strDate + " " + hours + ":" + min + ":" + sec;
return dateStr;
}
export function formatTime(timestamp) {
if (!timestamp) {
return "";
}
let date = new Date(timestamp);
let month = date.getMonth() + 1;
let strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
let dateStr =
date.getFullYear() +
"-" +
month +
"-" +
strDate +
" " +
(date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) +
":" +
(date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
":" +
(date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds());
return dateStr;
}
export function newDate() {
let date = new Date();
let month = date.getMonth() + 1;
let strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
let dateStr = date.getFullYear() + "-" + month + "-" + strDate;
return dateStr;
}
export function beforeDate(n) {
let date = new Date().getTime();
date = date - n * 24 * 60 * 60 * 1000;
return formatDate(date);
}
Date.prototype.format = function (fmt) {
let o = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
S: this.getMilliseconds(),
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(
RegExp.$1,
(this.getFullYear() + "").substr(4 - RegExp.$1.length)
);
for (let k in o)
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
);
return fmt;
};
export default Date;
3. 字符串的截取
export function subString(str, n) {
if (!n) return str;
let sign = str.length <= n ? "" : "...";
return str.substring(0, n) + sign;
}
4.判断当前元素是否是数组
*
* @param {
constructor} value
* @returns
*/
function isArray(value) {
return value && typeof value == "object" && value.constructor === Array;
}
function isArray(value) {
return value && typeof value == "object" && value instanceof Array;
}
function isArray(value) {
return (
Array.isArray(value) ||
(typeof value == "object" &&
Object.prototype.toString.call(value) === "[object Array]")
);
}
5.判断是否是对象
function isObject(value) {
return (
value != null &&
typeof value === "object" &&
Object.prototype.toString.call(value) === "[object Object]"
);
}
6.判断浏览器环境
function isAndroid() {
return (
/Android/i.test(navigator.userAgent) || /Linux/i.test(navigator.appVersion)
);
}
function isIOS() {
return /ipad|iphone/i.test(navigator.userAgent);
}
function isSafari() {
return /msie|applewebkit.+safari/i.test(navigator.userAgent);
}
function isWeixin() {
return /MicroMessenger/i.test(navigator.userAgent);
}
7.使用promise封装ajax(对jq的ajax的封装)
function $ajax(config) {
return new Promise(function (resolve, reject) {
$.ajax(
$.extend({
}, config, {
success: function (data) {
if (data && data.success === false) {
reject(data);
} else {
resolve(data);
}
},
error: function (...args) {
console.error(config, ...args);
reject(...args);
},
})
);
});
}
function ajax(config) {
return new Promise(function (resolve, reject) {
$.ajax(
$.extend(
{
xhrFields: {
withCredentials: true,
},
crossDomain: true,
},
config,
{
success: function (data) {
if (data && data.success === false) {
reject(data);
} else {
resolve(data);
}
},
error: function (...args) {
console.error(config, ...args);
reject(...args);
},
}
)
);
});
}
8.获取滚动的高度
export const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop,
});
export const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
};
export const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
const {
top, left, bottom, right } = el.getBoundingClientRect();
const {
innerHeight, innerWidth } = window;
return partiallyVisible
? ((top > 0 && top < innerHeight) ||
(bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
};
9.洗牌算法随机
export const shuffle = (arr) => {
let result = [],
random;
while (arr.length > 0) {
random = Math.floor(Math.random() * arr.length);
result.push(arr[random]);
arr.splice(random, 1);
}
return result;
};
10.劫持粘贴板
export const copyTextToClipboard = (value) => {
let textArea = document.createElement("textarea");
textArea.style.background = "transparent";
textArea.value = value;
document.body.appendChild(textArea);
textArea.select();
try {
let successful = document.execCommand("copy");
} catch (err) {
console.log("Oops, unable to copy");
}
document.body.removeChild(textArea);
};
11.判断类型集合
export const checkStr = (str, type) => {
switch (type) {
case "phone":
return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str);
case "tel":
return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
case "card":
return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
case "pwd":
return /^[a-zA-Z]\w{5,17}$/.test(str);
case "postal":
return /[1-9]\d{5}(?!\d)/.test(str);
case "QQ":
return /^[1-9][0-9]{4,9}$/.test(str);
case "email":
return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
case "money":
return /^\d*(?:\.\d{0,2})?$/.test(str);
case "URL":
return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(
str
);
case "IP":
return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(
str
);
case "date":
return (
/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(
str
) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str)
);
case "number":
return /^[0-9]$/.test(str);
case "english":
return /^[a-zA-Z]+$/.test(str);
case "chinese":
return /^[\\u4E00-\\u9FA5]+$/.test(str);
case "lower":
return /^[a-z]+$/.test(str);
case "upper":
return /^[A-Z]+$/.test(str);
case "HTML":
return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
default:
return true;
}
};
12.严格的身份证校验和身份证城市
export const isCardID = (sId) => {
if (!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(sId)) {
console.log("你输入的身份证长度或格式错误");
return false;
}
let aCity = {
11: "北京",
12: "天津",
13: "河北",
14: "山西",
15: "内蒙古",
21: "辽宁",
22: "吉林",
23: "黑龙江",
31: "上海",
32: "江苏",
33: "浙江",
34: "安徽",
35: "福建",
36: "江西",
37: "山东",
41: "河南",
42: "湖北",
43: "湖南",
44: "广东",
45: "广西",
46: "海南",
50: "重庆",
51: "四川",
52: "贵州",
53: "云南",
54: "西藏",
61: "陕西",
62: "甘肃",
63: "青海",
64: "宁夏",
65: "新疆",
71: "台湾",
81: "香港",
82: "澳门",
91: "国外",
};
if (!aCity[parseInt(sId.substr(0, 2))]) {
console.log("你的身份证地区非法");
return false;
}
13.出生日期验证和身份证号码校验
let sBirthday = (
sId.substr(6, 4) +
"-" +
Number(sId.substr(10, 2)) +
"-" +
Number(sId.substr(12, 2))
).replace(/-/g, "/"),
d = new Date(sBirthday);
if (
sBirthday !=
d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate()
) {
console.log("身份证上的出生日期非法");
return false;
}
let sum = 0,
weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2],
codes = "10X98765432";
for (let i = 0; i < sId.length - 1; i++) {
sum += sId[i] * weights[i];
}
let last = codes[sum % 11];
if (sId[sId.length - 1] != last) {
console.log("你输入的身份证号非法");
return false;
}
return true;
};
14.随机数范围
export const random = (min, max) => {
if (arguments.length === 2) {
return Math.floor(min + Math.random() * (max + 1 - min));
} else {
return null;
}
};