个人收藏常用JS方法

/**
 *格式化时间
 *yyyy-MM-dd hh:mm:ss
 */
export function formatDate(time, fmt) {
  if (time === undefined || "") {
    return;
  }
  // 兼容ios
  if ((time + "").indexOf("-") != -1) time = time.replace(/\-/g, "/");

  const date = new Date(time);
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  const o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds()
  };
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = o[k] + "";
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : padLeftZero(str)
      );
    }
  }
  return fmt;
}
function padLeftZero(str) {
  return ("00" + str).substr(str.length);
}

// 转为unicode 编码
export function encodeUnicode(str) {
  var res = [];
  for (var i = 0; i < str.length; i++) {
    res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4);
  }
  return "\\u" + res.join("\\u");
}
/**
 * Parse the time to string
 * console.log(parseTime(new Date(), "{y}.{m}.{d} {h}.{i}.{s}.{a}"));
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    }
    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    if (result.length > 0 && value < 10) {
      value = "0" + value;
    }
    return value || 0;
  });
  return time_str;
}

//获取当前周详细信息
export function weekAndDate(date) {
  if (!date) date = new Date();
  const formatDate = function(date) {
    const year = date.getFullYear() + "-";
    const month = date.getMonth() + 1 + "-";
    const day = date.getDate();
    const week = ["日", "一", "二", "三", "四", "五", "六"][date.getDay()];
    // console.log(week)
    // return { date: `${year}${month < 10 ? '0'+month : month}${day < 10 ? '0'+day : day}`, week };
    return { date: `${year}${month}${day}`, week };
  };
  let dateArr = [];
  // 设置起始日期获取时间
  const week = date.getDay() - 1;
  date = addDate(date, week * -1);
  // currentFirstDate = new Date(date);
  //获取七天日期和周信息
  for (let i = 0; i < 7; i++) {
    const formatDates = formatDate(i == 0 ? date : addDate(date, 1));
    dateArr.push(formatDates);
  }
  return dateArr;
}
function addDate(date, n) {
  date.setDate(date.getDate() + n);
  return date;
}

// 解决精准度
export function parseFloatNum(num) {
  return parseFloat(num.toPrecision(12));
}
// 验证身份证号
export function
validateIdCard(idCard) { //15位和18位身份证号码的正则表达式 var regIdCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/; //如果通过该验证,说明身份证格式正确,但准确性还需计算 if (regIdCard.test(idCard)) { if (idCard.length == 18) { var idCardWi = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); //将前17位加权因子保存在数组里 var idCardY = new Array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2); //这是除以11后,可能产生的11位余数、验证码,也保存成数组 var idCardWiSum = 0; //用来保存前17位各自乖以加权因子后的总和 for (var i = 0; i < 17; i++) { idCardWiSum += idCard.substring(i, i + 1) * idCardWi[i]; } var idCardMod = idCardWiSum % 11;//计算出校验码所在数组的位置 var idCardLast = idCard.substring(17);//得到最后一位身份证号码 //如果等于2,则说明校验码是10,身份证号码最后一位应该是X if (idCardMod == 2) { if (idCardLast == "X" || idCardLast == "x") { return true; //alert("恭喜通过验证啦!"); } else { return false; //alert("身份证号码错误!"); } } else { //用计算出的验证码与最后一位身份证号码匹配,如果一致,说明通过,否则是无效的身份证号码 if (idCardLast == idCardY[idCardMod]) { //alert("恭喜通过验证啦!"); return true; } else { return false; //alert("身份证号码错误!"); } } } } else { //alert("身份证格式不正确!"); return false; } }
// 深克隆
export function deepClone(source) {
  if (typeof source !== 'object' || source === null) {
    return source;
  }
  const target = Array.isArray(source) ? [] : {};
  for (const [key, value] of Object.entries(source)) {
    target[key] = deepClone(value);
  }
  return target;
}
/**
 * 获取url中的查询字符串参数
 * @param {String} url  url字符串
 */
export function getURLParams(url) {
  const search = url.split('?')[1];
  if (!search) {
    return {}
  }
  return JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
}
// 获取元素相对于浏览器窗口边缘的的距离
export function getOffset(elem) {
  function getLeft(o) {
    if (o == null) {
      return 0;
    } else {
      return o.offsetLeft + getLeft(o.offsetParent) + (o.offsetParent ? o.offsetParent.clientLeft : 0);
    }
  }

  function getTop(o) {
    if (o == null) {
      return 0;
    } else {
      return o.offsetTop + getTop(o.offsetParent) + (o.offsetParent ? o.offsetParent.clientTop : 0);
    }
  }
  return { left: getLeft(elem), top: getTop(elem) };
}
// 节流
export function throttle(fn, interval = 100) {
  let timer = null;
  return function() {
    const context = this;
    const args = arguments;
    if (!timer) {
      timer = setTimeout(() => {
        timer = null;
        fn.apply(context, args)
      }, interval)
    }
  }
}

// 防抖
export function debounce(fn, interval = 100) {
  let timer = null;
  return function() {
    const context = this;
    const args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(context, args)
    }, interval)
  }
}
// 判断数据类型
export const getType = value => value ? value.constructor.name.toLowerCase() : value;
// 加载第三方脚本
export function loadScript(src, callback = (err, res) => {}) {
  const existScript = document.getElementById(src);
  if (existScript) {
    callback(null, existScript);
  } else {
    const script = document.createElement('script');
    script.src = src;
    script.id = src;
    document.body.appendChild(script);
    script.onload = function() {
      callback(null, script)
    }
    script.onerror = function() {
      callback(new Error(`“${src}”加载失败`), script)
    }
  }
}
// 隐藏银行卡中间号码
export const hideBankCard = (value) => {
  if (value && value.length > 8) {
    return `${value.substring(0, 4)} ${"*".repeat(value.length - 8).replace(/(.{4})/g, `$1 `)}${value.length % 4 ? " " : ""}${value.slice(-4)}`;
  }
  return value;
}
 
console.log(hideBankCard(6212261611110000222)) 
//打印结果 6212 **** **** *** 0222


export const number=(value)=>{
  if(value&&value.length>8) {
    let reg = /^(\d{4})(\d*)(\d{4})$/;
    let str = value.replace(reg, (a, b, c, d)=> {
      return b + c.replace(/\d/g, "*") + d;
    });
    return str
  }else {
    return value
  }
}
 
console.log(number('6212261611110000222'));
//打印结果 6212***********0222

//借鉴自https://blog.csdn.net/qq_45062261/article/details/106189067
// 千分位格式

const numFilter = num => {
// console.log(num.toString())
if (!num && num + "" !== "0") {
return "---";
}
num = num + "";
if (!num.includes(".")) {
num += ".";
}
return num
.replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) {
return $1 + ",";
})
.replace(/\.$/, "");
};

/*
 * 验证密码输入规则
 */
export function passwordRule(phone) {
  if (!phone) {
    alert("不能为空");
    return false;
  }
  //密码必须包含数字和字母
  //密码长度8到16位
  var regex = /(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,16}/;
  if (!regex.test(phone)) {
    alert("您的工号为弱口令密码,请修改密码后登录");
    return false;
  }
  //密码必须包含特殊字符 _&#%
  if (
    !(
      phone.indexOf("_") != -1 ||
      phone.indexOf("&") != -1 ||
      phone.indexOf("#") != -1 ||
      phone.indexOf("%") != -1
    )
  ) {
    alert("弱口令密码");
    return false;
  }
  //不能连续字符(如123、abc)连续3位或3位以上
  if (!LxStr(phone)) {
    alert("弱口令密码");
    return false;
  }
  //不能相同字符(如111、aaa)连续3位或3位以上
  var re = /(\w)*(\w)\2{2}(\w)*/g;
  if (re.test(phone)) {
    alert("弱口令密码");
    return false;
  }
}
const LxStr = function(str) {
  var arr = str.split("");
  var flag = true;
  for (var i = 1; i < arr.length - 1; i++) {
    var firstIndex = arr[i - 1].charCodeAt();
    var secondIndex = arr[i].charCodeAt();
    var thirdIndex = arr[i + 1].charCodeAt();
    thirdIndex - secondIndex == 1;
    secondIndex - firstIndex == 1;
    if (thirdIndex - secondIndex == 1 && secondIndex - firstIndex == 1) {
      flag = false;
    }
  }
  return flag;
};
//网址校验
  website(value) {
    const reg = /((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)/;
    return reg.test(value);
  }  
// 全角转半角
function ToCDB(str) {
  var tmp = "";
  for (var i = 0; i < str.length; i++) {
    if (str.charCodeAt(i) > 65248 && str.charCodeAt(i) < 65375) {
      tmp += String.fromCharCode(str.charCodeAt(i) - 65248);
    } else {
      tmp += String.fromCharCode(str.charCodeAt(i));
    }
  }
  return tmp;
}
//luhn银行卡号校验
export function testBankNum(payCard) {
  console.log(payCard);
  // 没有传银行卡
  if (!payCard) {
    return true;
  }
  // 非数字
  if (isNaN(payCard)) {
    return false;
  }
  // 银行卡位数为16或19位
  if (String(payCard).length !== 16 && String(payCard).length !== 19) {
    return false;
  }
  const everyNum = String(payCard).split(""); // 将银行卡的所有数字拆分
  everyNum.forEach((num, index) => {
    if (index % 2 === 0) {
      // 从右往左  偶数位
      num = Number(num).toString(2) + "0"; // 转换为二进制,并将二进制左移一位
      num = parseInt(num, 2); // 转回十进制
      num = ((num / 10) | 0) + (num % 10); // 当前数字每位的和
      everyNum[index] = num;
    }
  });
  return everyNum.reduce((tol, num) => tol + parseInt(num), 0) % 10 === 0; // 统计总和 % 10是否整除
}

 

//邮箱验证规则
 /^([A-Za-z0-9_\-.])+@([A-Za-z0-9_\-.])+(.[a-zA-Z0-9_-]+)+$/;
/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

 

//获取域名 
const url = "http://www.example.com/path/to/page.html";
const domain = url.match(
  /^(?:https?:\/\/)?(?: [^@\n]+@)?(?:w.)?([^:\/\n]+)/im
)[1];
console.log(domain);

 

持续更新中.......

posted on 2020-11-10 16:49  写最骚的代码  阅读(169)  评论(0编辑  收藏  举报