常用的正则校验

生成指定范围的随机整数

const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
randomIntegerInRange(0, 5);

生成指定范围的随机小数

const randomNumberInRange = (min, max) => Math.random() * (max - min) + min;
randomNumberInRange(2, 10);

四舍五入到指定位数

const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
round(1.005, 2);

精确小数

const RoundNum = (num, decimal) =>Math.round(num * 10 ** decimal) / 10 ** decimal;const num = RoundNum(1.69, 1);// num => 1.7

简单的货币单位转换

const toCurrency = (n, curr, LanguageFormat = undefined) =>
  Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n);
  
toCurrency(123456.789, 'EUR'); // €123,456.79
toCurrency(123456.789, 'USD', 'en-us'); // $123,456.79  
toCurrency(123456.789, 'USD', 'fa'); // ۱۲۳٬۴۵۶٫۷۹
toCurrency(322342436423.2435, 'JPY'); // ¥322,342,436,423 

随机十六进制颜色

const randomHexColorCode = () => {
  let n = (Math.random() * 0xfffff * 1000000).toString(16);
  return '#' + n.slice(0, 6);
};

randomHexColorCode();

奇偶判断  

const OddEven = num => !!(num & 1) ? "odd" : "even";const num = OddEven(2);// num => "even"

统计数组成员个数

const arr = [0, 1, 1, 2, 2, 2];const count = arr.reduce((t, v) => { t[v] = t[v] ? ++t[v] : 1; return t;}, {});// count => { 0: 1, 1: 2, 2: 3 }

数组中某元素出现的次数

export function countOccurrences(arr, value) {
    return arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0);
}

简单数组交集

export const similarity = (arr1, arr2) => arr1.filter(v => arr2.includes(v));

实现千位分隔符

// 保留三位小数
parseToMoney(1234.56); // return '1,234.56'
parseToMoney(123456789); // return '123,456,789'
parseToMoney(1087654.321); // return '1,087,654.321'
function parseToMoney(num) {
  num = parseFloat(num.toFixed(3));
  let [integer, decimal] = String.prototype.split.call(num, '.');
  integer = integer.replace(/\d(?=(\d{3})+$)/g, '$&,');
  return integer + '.' + (decimal ? decimal : '');
}
function parseToMoney(str){
    // 仅仅对位置进行匹配
    let re = /(?=(?!\b)(\d{3})+$)/g; 
   return str.replace(re,','); 
}

验证是否是身份证

function isCardNo(number) {
    var regx = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    return regx.test(number);
}

  

 

posted @ 2020-08-18 17:11  紫羽35  阅读(323)  评论(0编辑  收藏  举报