常用工具函数总结
1、将中文替换为指定的内容
function formateStrin(str) {
return str.replace(/([^u0000-u00FF])/g, function(match, key) {
console.log(111)
return "/"
})
};
formateStrin("我的123你是")////123/
2、获取url问号后面指定的值
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) {
return unescape(decodeURI(r[2]))
};
return null;
}
3、获取相对当前未来或以前的时间
/**
* 计算未来天数或以前的日期,相对当前日期
* @param {Number} num 未来天数传正数,以前天数传负数
* @param {String} chars 特殊字符 / -
*/
function getRelativeTime(num, chars) {
num = num || 0;
chars = chars || "";
var nowDate = new Date();
nowDate.setDate(nowDate.getDate() + num);
var month = (nowDate.getMonth()+1).toString();
var date = (nowDate.getDate()).toString();
return nowDate.getFullYear() + chars + (
month.length === 2 ? month : "0" + month
) + chars + (
date.length === 2 ? date : "0" + date
);
};
4、js正则去除字符串所有的空格和首尾空格
/**
* 去除所有的空格
*/
function clearAllSpace (str) {
if(typeof str === 'string') {
return str.replace(/s+/g, '');
}
return str;
}
/**
* 去除首尾的空格
*/
function clearSESpace (str) {
if(typeof str === 'string') {
return str.replace(/^s+|s+$/g, '');
}
return str;
}
5、获取当前时间,格式化
/**
* 格式化时间原型方法
* @param {String} fmt yyyy-MM-dd | yyyy-MM-dd hh:mm:ss
*/
Date.prototype.Format = function (fmt) {
var 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;
}
6、特殊字符正则校验:
function specialChars(val) {
return new RegExp("[`~!%@#$^&*()-/_=·|{}':;',\[\].<>/?~!@#¥……&*()——|{}【】‘;:”“'。,、?]").test(val)
}
7、随机生成32位uuid:
let uuid = ()=> {
var s = [];
var hexDigits = "0123456789abcdef" + (new Date()).getTime().toString(16);
for (var i = 0; i < 32; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
var uuid = s.join('').toUpperCase();
return uuid;
};
8、js去除字符串拼接末尾逗号
使用正则表达式:str.replace(/,$/gi, "")
9、自定义去除首尾空格
function trim(str){
return str.replace(/(^\s*)|(\s*$)/g, "");
}
阅读量(1754+)
点赞(1754)
评论列表
我要评论