前端常用js方法封装

身份证号正则验证

export const idcard = function IDCard(value) {
  let reg =
    /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
  // console.log("reg.test(value)", reg.test(value));
  return reg.test(value);
};

邮箱验证

export const checkEmail = function (email) {
  const reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
  return reg.test(email)
}

url验证

export const  checkURL = function (url) {
  const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
  return reg.test(url)
}

手机号正则验证

export const checkMobile = function checkMobiles(mobile) {
  return RegExp(/^1[3456789]\d{9}$/).test(mobile);
};

数组去除 “undefined” 去重

export const removeEmptyArrayEle = function removeEmptyArrayEle(arr) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] == "undefined" || arr[i] == null || arr[i] == "") {
      arr.splice(i, 1);
      i = i - 1;
    }
  }
  return Array.from(new Set(arr));
};

首字母大写

export const abcCase = function (str) {
  return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
}

下划线转驼峰

export const camelCase = function (str) {
  return str.replace(/_[a-z]/g, str1 => str1.substr(-1).toUpperCase())
}

数字转字符串

export const isNumberStr = function (str) {
  return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
}

buildUUID 随机uuid用于上传

export const buildUUID = function () {
  const hexList = [];
  for (let i = 0; i <= 15; i++) {
    hexList[i] = i.toString(16);
  }
  let uuid = "";
  for (let i = 1; i <= 36; i++) {
    if (i === 9 || i === 14 || i === 19 || i === 24) {
      uuid += "-";
    } else if (i === 15) {
      uuid += 4;
    } else if (i === 20) {
      uuid += hexList[(Math.random() * 4) | 8];
    } else {
      uuid += hexList[(Math.random() * 16) | 0];
    }
  }
  return uuid.replace(/-/g, "");
};

富文本操作

1、正常显示
export const formatRichText = function (html) {
  let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
    match = match.replace(/style="[^"]+"/gi, "").replace(/style='[^']+'/gi, "");
    match = match.replace(/width="[^"]+"/gi, "").replace(/width='[^']+'/gi, "");
    match = match
      .replace(/height="[^"]+"/gi, "")
      .replace(/height='[^']+'/gi, "");
    return match;
  });
  newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
    match = match
      .replace(/width:[^;]+;/gi, "max-width:100%;")
      .replace(/width:[^;]+;/gi, "max-width:100%;");
    return match;
  });
  newContent = newContent.replace(/<br[^>]*\/>/gi, "");
  newContent = newContent.replace(
    /\<img/gi,
    '<img style="margin:10px auto !important;"'
  );
  return newContent;
};
2、删除img
export const showHtml = function (str) {
  return str
    .replace(str ? /&(?!#?\w+;)/g : /&/g, "&amp;")
    .replace(/&lt;p&gt;&lt;br&gt;&lt;\/p&gt;/g, "")
    .replace(/^(\t)*$\n/g, "")
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'")
    .replace(/&rdquo;/g, "'")
    .replace(/&ldquo;/g, "'")
    .replace(/ldquo;/g, " ")
    .replace(/emsp;/g, " ")
    .replace(/&/g, " ")
    .replace(/amp;/g, " ")
    .replace(/mdash;/g, " ")
    .replace(/nbsp;/g, " ")
    .replace(/rdquo;/g, "")
    .replace(/&amp;nbsp;/g, "\u3000");
  // .replace(/ style=\"(.*)\"/g, "")
  // .replace(/<p> <\/span><\/p>/g, "")
  // .replace(/<p><span \/><\/span><\/p>/g, "")
};

节流

在一定时间内,只能触发一次
export const  throttle = function (func, wait = 500, immediate = true) {
	if (immediate) {
		if (!flag) {
			flag = true;
			// 如果是立即执行,则在wait毫秒内开始时执行
			typeof func === 'function' && func();
			timer = setTimeout(() => {
				flag = false;
			}, wait);
		}
	} else {
		if (!flag) {
			flag = true
			// 如果是非立即执行,则在wait毫秒内的结束处执行
			timer = setTimeout(() => {
				flag = false
				typeof func === 'function' && func();
			}, wait);
		}
	}
};

特殊字符检查

export const checkCharacter = function checkCharacter(str) {
  var regexp = new RegExp("[`~&_+*()]");
  if (regexp.test(str)) {
    return true;
  } else {
    return false;
  }
};

判断是否是图片

export const isImg = function (path) {
  return /\w.(png|jpg|jpeg|svg|webp|gif|bmp)$/i.test(path);
}

验证是否为blob格式

export const blobValidate = function (data) {
  try {
    const text = await data.text();
    JSON.parse(text);
    return false;
  } catch (error) {
    return true;
  }
}

下载文件

export const downloadFiles = function (filepath, filename) {
  let a = document.createElement("a");
  a.download = filename;
  a.href = filepath;
  a.target = "_blank";
  a.click();
  a.remove();
}

字典回显

export const selectDictLabel  =  function(data, value) {
  if (value === undefined || value === null || value === "") {
    return "";
  }
  let actions = [];
  Object.keys(data).some((key) => {
    if (key == value) {
      actions.push(data[value]);
      return true;
    }
  });
  if (actions.length === 0) {
    actions.push(value);
  }
  return actions.join("");
}

字典回显(字符串数组)

export const selectDictLabels = function(datas, value, separator) {
  if (value === undefined) {
    return "";
  }
  var actions = [];
  var currentSeparator = undefined === separator ? "," : separator;
  var temp = value.split(currentSeparator);
  Object.keys(value.split(currentSeparator)).some((val) => {
    var match = false;
    Object.keys(datas).some((key) => {
      if (datas[key].value == ('' + temp[val])) {
        actions.push(datas[key].label + currentSeparator);
        match = true;
      }
    })
    if (!match) {
      actions.push(temp[val] + currentSeparator);
    }
  })
  return actions.join('').substring(0, actions.join('').length - 1);
}

时间戳转年月日时分秒

export const timestampToTime = function timestampToTime(time, type) {
  var date = new Date(time * 1000);
  var Y = date.getFullYear() + "-";
  var M =
    (date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1) + "-";
  var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";

  var h =
    (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  var m = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  var s =
    ":" +
    (date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds());
  if (type == "y-m-d h-m-s") {
    return Y + M + D + h + m + s;
  } else if (type == "m-d") {
    return M + "月" + D + "日";
  } else if (type == "y-m-d h-m") {
    return Y + M + D + h + m;
  }
};

昨天、前天、今天显示几点、前天之前显示yy/mm/dd

export const timeago = function timeago(time) {
  if (typeof time === "number") {
    time = timestampToTime(time, "y-m-d h-m-s");
    time = time.substring(0, time.length - 3);
  } else {
    time = time.toString().substring(0, time.length - 3);
  }
  let str = time.split(" ")[0];
  let ptime = new Date(time).getTime();
  const twentyFourHours = 24 * 60 * 60 * 1000;
  const fortyEightHours = 24 * 60 * 60 * 1000 * 2;
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const today = `${year}-${month}-${day}`;
  const todayTime = new Date(today).getTime();
  const yesterdayTime = new Date(todayTime - twentyFourHours).getTime();
  const lastYesterdayTime = new Date(todayTime - fortyEightHours).getTime();
  if (year == new Date(time).getFullYear()) {
    if (ptime >= todayTime) {
      return time.split(" ")[1];
    } else if (ptime < todayTime && yesterdayTime <= ptime) {
      return "昨天 " + time.split(" ")[1];
    } else if (ptime < yesterdayTime && lastYesterdayTime <= ptime) {
      return "前天 " + time.split(" ")[1];
    } else {
      return (
        str.split("-")[1] + "-" + str.split("-")[2] + " " + time.split(" ")[1]
      );
    }
  } else {
    return time;
  }
};

刚刚、分钟前、小时前、天前、周前、半个月前、月前

export const timeago = function timeago(datetime) {
  var dateTimeStamp = new Date(datetime).getTime();
  var minute = 1000 * 60;
  var hour = minute * 60;
  var day = hour * 24;
  var week = day * 7;
  var halfamonth = day * 15;
  var month = day * 30;
  var now = new Date().getTime();
  var diffValue = Math.abs(now - dateTimeStamp); //时间差

  var minC = Math.floor(diffValue / minute); //计算时间差的分时天周月
  var hourC = Math.floor(diffValue / hour);
  var dayC = Math.floor(diffValue / day);
  var halfamonthC = Math.floor(diffValue / halfamonth);
  var weekC = Math.floor(diffValue / week);
  var monthC = Math.floor(diffValue / month);

  if (monthC > 0) {
    return monthC + "月前";
  }
  if (halfamonthC > 0) {
    return "半个月前";
  }
  if (weekC > 0) {
    return weekC + "周前";
  }
  if (dayC > 0) {
    return dayC + "天前";
  }
  if (hourC > 0) {
    return hourC + "小时前";
  }
  if (minC > 0) {
    return minC + "分钟前";
  }
  return "刚刚";
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值