js中常用方法功能

13 阅读1分钟

将身份证号码中间部分替换为星号

/**
 * 将身份证号码中间部分替换为星号
 * @param {string} idCard 身份证号码
 * @returns {string} 替换后的身份证号码
 */
export const maskIDCard = (idCard) => {
  if (idCard && idCard.length > 7) {
    let prefix = idCard.substring(0, 3); // 取前3位
    let suffix = idCard.substring(idCard.length - 4); // 取后4位
    let maskedPart = "*".repeat(idCard.length - 7); // 中间部分用星号代替
    return prefix + maskedPart + suffix;
  } else {
    return idCard; // 如果身份证号码过短,直接返回原字符串
  }
}

文件下载

/**
 * 文件下载
 * @param { string } url 下载地址
 * @param { string } fileName 下载名称
 */
export const downloadFile = (url, fileName) => {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'blob'; // 返回类型为 Blob

  xhr.onload = function () {
    if (xhr.status === 200) {
      // 创建一个临时 URL 对象
      const url = window.URL.createObjectURL(xhr.response);

      // 创建一个 <a> 标签进行下载
      const a = document.createElement('a');
      a.href = url;
      // 下载后文件名
      a.download = fileName;
      document.body.appendChild(a);
      a.click();

      // 清理 URL 对象
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    }
  };

  // 发送请求
  xhr.send();
}

判断文件地址是否为404并完成文件下载

/**
 * 判断文件地址是否为404并完成文件下载
 * @param { string } fileUrl 下载地址
 */
checkFileExists(fileUrl) {
  fetch(fileUrl)
    .then((response) => {
      if (response.status === 404) {
        this.$message.error("文件不存在,请检查文件地址。");
      } else {
        this.$message.success("文件存在,可以下载。");
        const xhr = new XMLHttpRequest();
        xhr.open("GET", fileUrl, true);
        xhr.responseType = "blob";
        xhr.onload = function () {
          if (this.status === 200) {
            const blob = this.response;
            const link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            link.download = "自定义文件名称.pdf";
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(link.href);
          }
        };
        xhr.send();
      }
    })
    .catch((error) => {
      console.error("请求出错:", error);
    });
},

获取地址栏上的参数

/**
 * 
 * @returns 获取url参数,返回对象
 */
export const getURLParams = () => {
  let url = window.location.href
  let params = {}
  let queryString = url.split('?')[1]
  if (queryString) {
    let pairs = queryString.split('&')
    for (let pair of pairs) {
      let [key, value] = pair.split('=')
      params[key] = decodeURIComponent(value)
    }
  }
  return params
}