一些常见的字符串和数组方法封装和日期格式化
一、字符串方法
1.字符串去空格
/**
*
* @param {*} str 需要处理的字符串
* @param {*} type 去除空格的
* 0-去除首尾空格 1-去除所有空格 2-去除首部空格 3-去除尾部空格
*/
function trim(str,type=0){
switch(type){
case 0:
return str.replace(/(^\s+)|(\s+$)/g,"");
case 1:
return str.replace(/\s+/g,"");
case 2:
return str.replace(/^\s+/g,"");
case 3:
return str.replace(/\s+$/g,"");
default:
return str;
}
}
2.字符串大小写转换
/**
*
* @param {*} str 需要处理的字符串
* @param {*} type 类型
* 0-大小写转换 1-小写 2-大写 3-首字母大写 4-首字母小写
*/
function changeCase(str,type=0){
function toggleCase(str){
let tempStr = ""
str.split("").forEach(item => {
if((/[a-z]/).test(item)){
tempStr += item.toUpperCase();
}else if(/[A-Z].test(item)/){
tempStr += item.toLowerCase();
}else{
tempStr += item;
}
});
return tempStr;
}
switch(type){
case 0:
return toggleCase(str);
case 1:
return str.toLowerCase();
case 2:
return str.toUpperCase();
case 3:
return str.substr(0,1).toUpperCase() + str.substr(1);
case 4:
return str.substr(0,1).toLowerCase() + str.substr(1);
default:
return str;
}
}
二、日期格式化
//格式化结果示例 2020-05-06 11:40 星期三
function dateFmt(str){
let date = new Date(str);
let fmt = "yyyy-MM-dd 星期D hh:mm";
function changeDay(day){
switch(day){
case 00:return "日";
case 01:return "一";
case 02:return "二";
case 03:return "三";
case 04:return "四";
case 05:return "五";
case 06:return "六";
}
}
let o = {
"M+":date.getMonth()+1,
"d+":date.getDate(),
"h+":date.getHours(),
"m+":date.getMinutes(),
"D":changeDay(date.getDay())
}
fmt = fmt.replace(/y+/g,date.getFullYear());
for(x in o){
let exp = new RegExp("("+ x +")")
if(x != "D"){
fmt = fmt.replace(exp,o[x]>9?o[x]:'0'+o[x]);
}else{
fmt = fmt.replace(exp,o[x]);
}
}
return fmt;
}
三、数组方法
//数组去重
function removeArrayRepeat(arr){
return Array.from(new Set(arr))
}
//数组打乱
function upsetArray(arr) {
return arr.sort(function () {
return Math.random() - 0.5
});
}
//数组最大值、最小值
function maxArray(arr) {
return Math.max.apply(null,arr)
}
function minArray(arr) {
return Math.min.apply(null,arr)
}
//数组求和、平均值
function sumArray(arr) {
let sum = 0;
arr.forEach(item=>{
sum += item
})
return sum;
}
function averArray(arr) {
let sum = this.sumArray(arr);
return sum/arr.length
}
//数组扁平化
function flatArray(arr) {
return arr.reduce(function(result,item){
return result.concat(Array.isArray(item)?flatArray(item):item)
},[])
}
最后将文件暴露即可。