常用正则表达式
1.判断是否是千分符字符
const numberIsThousand = str => /^-?\d{1,3}(,\d{3})*(\.\d+)?$/.test(str);
console.log(numberIsThousand('100,000,000,000.5')); // true
console.log(numberIsThousand('100,000,000,00')); // false
2.正则判断字符重复次数不超过两次
const strIsRepeatThan2 = (str = '') => /^(?!.*(.).*\1{2})[\da-zA-Z].+$/.test(str);
console.log(strIsRepeatThan2('2')); // TODO 单个字符有问题!
console.log(strIsRepeatThan2('21')); // true
console.log(strIsRepeatThan2('22')); // true
console.log(strIsRepeatThan2('222')); // false
3. 正则匹配可以只有 0 但开头不能是 0 的数字
const getCorrectNumber = (str = '') => /^(\d|[1-9]\d*)$/.test(str);
console.log(getCorrectNumber('0')); // true
console.log(getCorrectNumber('011')); // false
console.log(getCorrectNumber('101')); // true
金额的格式化
console.log('$ 12345678'.replace(/\B(?=(\d{3})+(?!\d))/g, ',')); // $ 12,345,678.12
console.log('$ 12,345,678'.replace(/\$\s?|(,*)/g, '')); // 12345678
console.log('$ 12345678.5678'.replace(/\B(?=(\d{3})+(?!\d)(?<!([.]\d+)))/g, ','));
/**
* 格式化金额 将以分为单位转化为以元为单位,2位小数 1,123,121.00
* @param {string | number} money - 120000
* @return {string} 120,000.00
*/
export const formateMoney = money =>
(Number(money) / 100).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
字符串去重
'aaazzbbbbssssgssdddddd'.replace(/(\w)\1*/g, '$1'); // "azbsd"
双大括号替换值
var str = "My name is {{name}}, I'm {{age}} years old",
reg = /{{(\w*?)}}/g;
var str1 = str.replace(reg, function (node, key) {
return {
name: '小明',
age: 18
}[key];
});
console.log(str1);
身份证
var reg = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
密码—至少 6 位,包含大写小写数字特殊字符
var reg = /^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[~!@#$%^&*]).*$/;
邮箱
var reg = /^([A-z0-9_-]+\@([A-z0-9_\-\.]+\.(A-z){2,4}))/;
电话号码
var str = '+86-010-1234567-123', // 086-...
reg = /^(([0/+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/g;
var str1 = str.match(reg);
console.log(str1);
手机号码
var reg = /^(?:\(\+86\))?(?:13[0-9]|14[57]|15[012356789]|17[0678]|18[0-9])\d{8}$/g;
生日
var reg = /^(19|20)\d{2}([-/.])(0[1-9]|1[0-2])\2(0[1-9]|[12][0-9]|3[012])/;
模板替换的常用讨论
<div class="artical"></div>
<script type="text/html" id="tpl">
<div class="wrap">
<h1>{{title}}</h1>
<h3>{{author}}</h3>
<p>{{content}}</p>
</div>
</script>
<script type="text/javascript">
var tpl = document.getElementById('tpl').innerHTML,
artical = document.getElementsByClassName('artical')[0];
var reg = /{{(.*?)}}/g;
artical.innerHTML = tpl.replace(reg, function (node, key) {
return {
title: '古悠悠行',
author: '李贺',
content: '白景归西山,碧华上迢迢。今古何处尽,千岁随风飘。海沙变成石,鱼沫吹秦桥。空光远流浪,铜柱从年消。'
}[key];
});
</script>