一些实用的js封装方法

921 阅读1分钟

以下这些是项目中用到的,封装的方法,如果有问题虚心求教。

正则手机号验证

function isMobile (mobile) {  
  return /^1[3-9]\d{9}$/.test(mobile)
}

截取url参数

function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}
getQueryObject('https//www.baidu.com?id=1111&type=edit')

格式化时间(方法1)

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
}
// 使用
parseTime(new Date(),'{y}-{m}-{d} {h}:{i}:{s}')

格式化时间(方法2)

/**
 * 格式化时间
 */
function NewTime(time) {
  if (!time) time = new Date()
  const t = new Date(time) // 你已知的时间
  t.setTime(t.setMinutes(t.getMinutes())) // 设置新时间比旧时间多一分钟
  const Y = t.getFullYear()
  let M = t.getMonth() + 1
  let D = t.getDate()
  let HH = t.getHours()
  let MM = t.getMinutes()
  let SS = t.getSeconds()
  if (M < 10) M = '0' + M
  if (D < 10) D = '0' + D
  if (HH < 10) HH = '0' + HH
  if (MM < 10) MM = '0' + MM
  if (SS < 10) SS = '0' + SS
  // let date_value = Y + '-' + M + '-' + D + ' ' + HH + ':' + MM + ':' + SS;
  const date_value = Y + '-' + M + '-' + D + ' ' + HH + ':' + MM + ':' + SS
  return date_value
}

存储、获取、删除 sessionStorage

function __setItem(name, content) {
  if (!name) return;
  if (typeof content !== 'string') {
    content = JSON.stringify(content);
  }
  window.sessionStorage.setItem(name, content);
};

function __getItem(name) {
  if (!name) return;
  return window.sessionStorage.getItem(name);
};


function __removeItem(name) {
  if (!name) return;
  window.sessionStorage.removeItem(name);
};

检测手机号

function _isMobile(mobile) {
  var reg = /^[1][3,4,5,7,8][0-9]{9}$/;
  if (reg.test(mobile)) return true;
  else return false;
};

将base64转换为文件

function dataURLtoFile(dataurl, filename) {
  var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}

替换电话号码中间四位

function replacePhone(num) {
  let mphone = num;
  if (_isMobile(num)) {
    mphone = num.substr(0, 3) + '****' + num.substr(7);
  }
  return mphone;
};

去除内容中的空格

function deblank(str) {
  str = str.replace(/\s*/g, '');
  return str;
};

电话号码格式344替换

function phoneSeparated(num) {
  let mphone = num;
  if (_isMobile(num)) {
    mphone =
      num.substring(0, 3) +
      ' ' +
      num.substring(3, 7) +
      ' ' +
      num.substring(7, 11);
  }
  return mphone;
};

银行卡格式4444替换

function cardSeparated(num) {
  let index = num ? num.length / 4 : 0;
  let result = '';
  for (let i = 0; i < index; i++) {
    result += num.substring(i * 4, (i + 1) * 4) + ' ';
  }
  return result;
};

身份证格式生日替换

function identityCardSeparated(num) {
  if (num.length === 18) {
    var str = num.substr(0, 6) + '********' + num.substr(14);
    return str;
  } else {
    return num;
  }
};

护照号替换

function passportSeparated(num) {
  if (num.length > 4) {
    var str = num.substr(0, num.length - 4) + '****';
    return str;
  } else {
    return num;
  }
};

卡号每隔四位加短线

function cardNoFormat(cardNo) {
  if (typeof cardNo == 'number') {
    cardNo = String(cardNo).replace(/\D/g, '').replace(/....(?!$)/g, '$&-');
  } else {
    cardNo = cardNo.replace(/\D/g, '').replace(/....(?!$)/g, '$&-');
  }
  return cardNo;
};
console.log(cardNoFormat('124141251512'))
console.log(cardNoFormat(1233124124124124))

简单的深拷贝 deepClone

function deepClone(data) {
  if (!data && typeof data !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const obj = data.constructor === Array ? [] : {}
  Object.keys(data).forEach(keys => {
    if (data[keys] && typeof data[keys] === 'object') {
      obj[keys] = deepClone(data[keys])
    } else {
      obj[keys] = data[keys]
    }
  })
  return obj
}
var arr = [1,2,3,4,5,6];
console.log(deepClone(arr))

arr = [...arr, ...[7,8,9]]
console.log(arr, 'arr')

每隔四位加空格

function fourSpace(num) {
  var value = num
    .replace(/\D/g, '')
    .replace(/....(?!$)/g, '$& ');
  return value;
};
fourSpace('13122223333')

身份证校验

function IdentityCodeValid(code) {
  let city = {
    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: '国外'
  };
  let tip = '';
  let pass = true;
  if (!code || !/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(code)) {
    tip = '身份证号格式错误';
    pass = false;
  } else if (!city[code.substr(0, 2)]) {
    tip = '地址编码错误';
    pass = false;
  }
  if (!pass) message.error(tip);
  return pass;
};

HmacSHA256加密

function encryptHmacSHA256(value) {
  const userInfo = getUserInfo();
  let key = '';
  if (userInfo.data) {
    key = userInfo.data.publicKey;
  }
  let ciphertext = CryptoJS.HmacSHA256(value, key);
  let hashInBase64 = CryptoJS.enc.Base64.stringify(ciphertext);
  return hashInBase64;
};

对象中的null转为空字符串

function _replaceNull(obj) {
  if (typeof obj === 'object') {
    Object.keys(obj).forEach(element => {
      let value = obj[element];
      if (value === null || value === undefined) {
        // obj[element] = '';
        delete obj[element];
      } else if (typeof value === 'object') {
        _replaceNull(value);
      }
    });
  }
  return obj;
};

文件导出

function _checkoutFile(fileName, response) {
  console.log('response');
  console.log(response);
  let blob = new Blob([response], { type: 'application/vnd.ms-excel' });
  let objectUrl = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.setAttribute('href', objectUrl);
  a.setAttribute('download', fileName);
  a.click();
  URL.revokeObjectURL(objectUrl);
};

url文件导出

function _urlExportFile(url) {
  const a = document.createElement('a');
  a.setAttribute('href', url);
  a.click();
};

url校验

function validateURL(url, list) {
  let i = 0;
  if (list) {
    list.forEach(el => {
      if (url === el) {
        i = 1;
      }
    });
  }
  if (i !== 0) return false;
  if (i === 0) return true;
};

页面可视高度、 页面可视宽度

function clientHeight() {
  let clientHeight = document.getElementById('root').clientHeight;
  let offsetHeight = document.getElementById('root').offsetHeight;
  return clientHeight || offsetHeight;
};

function clientWidth() {
  let clientWidth = document.getElementById('root').clientWidth;
  let offsetWidth = document.getElementById('root').offsetWidth;
  return clientWidth || offsetWidth;
};

格式化金额

function formatMoney(val) {
  var valStr = String(Number(val).toFixed());
  var prefix_val, suffix_val, prefix_result, prefix_arr = null;
  var j, t, i = 0;
  let negativeFlag = false; //负数
  if (isNaN(Number(valStr))) {
    return val
  }
  if(Number(valStr) < 0){
    negativeFlag = true;
    valStr = String(Math.abs(valStr))
  }
  if (valStr.length < 3) {
    valStr = prefix(valStr, 3)
  }
  prefix_val = valStr.slice(0, -2)
  suffix_val = valStr.slice(-2)
  prefix_result = []
  prefix_arr = prefix_val.split("")
  j = 0
  t = 3
  for (i = prefix_arr.length - 1; i >= 0; i--) {
    j++
    if (j === t || i === 0) {
      prefix_result.unshift(prefix_arr.splice(i).join(""))
      j = 0
    }
  }
  if(negativeFlag){
    return '-' + prefix_result.join(",") + "." + suffix_val
  }else{
    return prefix_result.join(",") + "." + suffix_val
  }
}
formatMoney(1111111)

格式化金额2

// 格式化金额
export function numberFormat (val: any) {
    let unit = '';
    var k = 10000, sizes = ['', '万', '亿'], i;
    if(val < k) {
        val = val;
    } else {
        i = Math.floor(Math.log(val) / Math.log(k));
        val = ((val / Math.pow(k, i))).toFixed(2);
        unit = sizes[i];
    }
    return val + unit;
}