JS 常用方法合集

JS 大、小写字母相互转换

this.letterConvert("ASD", false) // 大写转为小写 - asd

this.letterConvert("abc", true) // 小写转为大写 - ABC

/** 大小写字母转换
 * @param e 需要转换的字母
 * @param capital true.转为大写 false.转为小写
 * @returns {string} 转换后的字母
 */
letterConvert(e, capital = false) {
  if (!e) return "";
  let result = e.toLowerCase();
  if (capital) result = e.toUpperCase();
  return result;
},

JS 身份证号脱敏

this.idCardDesensitize("110101200411239598") // 1101******9598

/** 身份证号脱敏
 * @param card 需要脱敏的身份证号
 * @returns {string} 已脱敏的身份证号
 */
idCardDesensitize(card) {
  if (!card) return "";
  return card.replace(/^(.{4})(?:\d+)(.{4})$/, "$1******$2");
},

JS 手机号码脱敏

this.phoneDesensitize("15078459842") // 150****9842

/** 手机号脱敏
 * @param tel 需要脱敏的手机号
 * @returns {string} 已脱敏的手机号
 */
phoneDesensitize(tel) {
  if (!tel) return "";
  return tel.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
},

JS 获取文件名

this.getFileNameSuffix("测试文件.txt", true, false) // txt

this.getFileNameSuffix("测试文件.txt", true, true) // .txt

this.getFileNameSuffix("测试文件.txt") // 测试文件

/** 获取文件名或文件后缀
 * @param file 目标文件地址
 * @param isSuffix true.获取文件后缀 false.获取文件名
 * @param isDot true.需要后缀前面的. false.不需要后缀前面的.
 * @returns {string} 返回的文件名或文件后缀
 */
getFileNameSuffix(file, isSuffix = false, isDot = false) {
  if (!file) return "";
  let result = "";
  const pos = file.lastIndexOf(".");
  result = file.substring(0, pos);
  if (isSuffix) result = file.substring(pos + (isDot ? 0 : 1));
  return result;
},

 JS 文件大小转换

this.getFileSize(123) // 123B

/** 文件大小转换
 * @param size 需要转换的文件大小
 * @returns {string|number} 结果
 */
getFileSize(size) {
  if (!size) return 0;
  const num = 1024.0; // Byte
  if (size < num) {
    return size + "B";
  }
  if (size < Math.pow(num, 2)) {
    return (size / num).toFixed(2) + "KB";
  }
  if (size < Math.pow(num, 3)) {
    return (size / Math.pow(num, 2)).toFixed(2) + "M";
  }
  if (size < Math.pow(num, 4)) {
    return (size / Math.pow(num, 3)).toFixed(2) + "G";
  }
  return (size / Math.pow(num, 4)).toFixed(2) + "T";
},

JS 去除字符串内的空格(空白符)

this.purgeStrSpace("  测  试  的 文  本  ") // 测试的文本

/** 去除字符串内的空格(空白符)
 * @param str 需要去空格的字符串
 * @param type all.去除所有空格 bothSides.去除两头空格 left.去除左侧空格 right.去除右侧空格
 * @returns {string} 已处理好的字符串
 */
purgeStrSpace(str, type = "all") {
  if (!str) return "";
  let result = str.replace(/\s*/g, ""); // 去除字符串内所有的空格
  if (type === "bothSides") result = str.replace(/^\s*|\s*$/g, ""); // 去除字符串内两头的空格
  if (type === "left") result = str.replace(/^\s*/, ""); // 去除字符串内左侧的空格
  if (type === "right") result = str.replace(/(\s*$)/g, ""); // 去除字符串内右侧的空格
  return result;
},

JS 去掉指定的字符

this.purgeSpecifyStr("str-in-g-") // string

/** 去掉指定的字符
 * @param str 需要操作的字符串
 * @param char 指定要替换的字符
 * @returns {string|*} 操作完成的字符串
 */
purgeSpecifyStr(str, char = "-") {
  if (!str) return "";
  return str.replace(new RegExp(char, "g"), "");
},

JS 小数取整

丢弃小数部分,保留整数部分(类似于向下取整):parseInt(String)

let num = 7 / 2;
num = num.toString(); // 如果不转化为字符串,parseInt() 会报:Argument type number is not assignable to parameter type string
console.log(parseInt(num)); // 3

向上取整,只要有小数,整数部分就加1:Math.ceil(Number)

let num = 7 / 2;
console.log(Math.ceil(num)); // 4

四舍五入:Math.round(Number)

let num = 7 / 2;
console.log(Math.round(num)); // 4

向下取整:Math.floor(Number)

let num = 7 / 2;
console.log(Math.floor(num)); // 3

JS 数字格式化

this.formatNum(123456.9) // 123,456.90

/** 数字格式化(金额格式化)
 * @param num 要格式化的数字
 * @param digit 保留几位小数(值为 0 时四舍五入)
 * @param pointSign 小数点符号
 * @param thousandSign 千分位符号
 * @returns {string} 结果
 */
formatNum(num = 0, digit = 2, pointSign = ".", thousandSign = ",") {
  num = (num + "").replace(/[^\d+-Ee.]/g, "");
  let result = "",
    toFixedFix = function (num, digit) {
      const k = Math.pow(10, digit);
      return "" + Math.ceil(num * k) / k;
    };
  const isRound = digit ? toFixedFix(num, digit) : "" + Math.round(num);
  result = isRound.split(".");
  const re = /(-?\d+)(\d{3})/;
  while (re.test(result[0])) {
    result[0] = result[0].replace(re, "$1" + thousandSign + "$2");
  }
  if ((result[1] || "").length < digit) {
    result[1] = result[1] || "";
    result[1] += new Array(digit - result[1].length + 1).join("0");
  }
  return result.join(pointSign);
},

JS 移除数字格式化

this.removeFormat("123,456.9") // 123456.9

/** 移除数字格式化
 * @param e 目标内容
 * @returns {number} 结果
 */
removeFormat(e) {
  if (!e) return "";
  return parseFloat(e.replace(/[^\d.-]/g, ""));
},

JS 数字位数不够,数字前面补零

this.prefixZero(5) // 05

/** 数字位数不够,数字前面补零
 * @param num 需要补零的数
 * @param n 需要补几个零
 * @returns {string} 结果
 */
prefixZero(num = 0, n = 2) {
  return (Array(n).join("0") + num).slice(-n);
},

JS 将大额数值转化以千、万、亿等单位

this.unitTransform(108780, 1) // 10.9万

/** 将大额数值转化以千、万、亿等单位(如:点赞数)
 * @param val 需要转换的数值
 * @param digit 保留几位小数(四舍五入法)
 * @returns {string} 结果
 */
unitTransform(val, digit = 0) {
  let nVal = ["", "", ""],
    fr = 1000,
    num = 3;
  while (val / fr >= 1) {
    fr *= 10;
    num += 1;
  }
  // 千级单位
  if (num <= 4) {
    nVal[1] = "千";
    nVal[0] = parseInt((val / 1000).toString()) + "";
  }
  // 万级单位
  else if (num <= 8) {
    const str = parseInt((num - 4).toString()) / 3 > 1 ? "千万" : "万";
    const fm = "万" === str ? 10000 : 10000000;
    nVal[1] = str;
    nVal[0] = val / fm + "";
  }
  // 亿级单位
  else if (num <= 16) {
    let str = (num - 8) / 3 > 1 ? "千亿" : "亿";
    str = (num - 8) / 4 > 1 ? "万亿" : str;
    str = (num - 8) / 7 > 1 ? "千万亿" : str;
    let fm = 1;
    if (str === "亿") fm = 100000000;
    else if (str === "千亿") fm = 100000000000;
    else if (str === "万亿") fm = 1000000000000;
    else if (str === "千万亿") fm = 1000000000000000;
    nVal[1] = str;
    nVal[0] = parseInt((val / fm).toString()) + "";
  }
  // 千级以下
  if (val < 1000) {
    nVal[1] = "";
    nVal[0] = val + "";
  }
  nVal[0] = parseFloat(nVal[0]).toFixed(digit); // 保留多少位小数
  return nVal.join("");
},

JS 对包含 0 的值进行检查

this.valCheck(0, 2) // true

this.valCheck(2) // 2

this.valCheck("张三") // 张三

/** 对包含 0 的值进行检查
 * @param e 需要检查的值
 * @param t 返回类型 1.返回原值 2.返回布尔类型
 * @param defVal 返回的默认值
 * @returns {string} 最终返回结果
 */
valCheck(e, t = 1, defVal = "") {
  let val = defVal;
  if (typeof (e) != "undefined" && e != null && !(e < 0)) val = e;
  if (t === 2 && typeof (e) != "undefined" && e != null && !(e < 0)) {
    val = true;
  } else if (t === 2) {
    val = false;
  }
  return val;
},

猜你喜欢

转载自blog.csdn.net/AdminGuan/article/details/128000997