工作中遇到的正则 持续更新...

228 阅读1分钟

保留2位小数 不四舍五入 不补零

dis.toString().match(/^\d+(?:\.\d{0,2})?/)

  • '0'.toString().match(/^\d+(?:\.\d{0,2})?/) // 0
  • '0.00'.toString().match(/^\d+(?:\.\d{0,2})?/) // 0.00
  • '10.00'.toString().match(/^\d+(?:\.\d{0,2})?/) // 10.00
  • '0.02'.toString().match(/^\d+(?:\.\d{0,2})?/) // 0.02

匹配年份以2开头,且4位数

^[2][0-9]{3}?$

  • /^[2][0-9]{3}?$/.test(2005) // true
  • /^[2][0-9]{3}?$/.test(1005) // false
  • /^[2][0-9]{3}?$/.test(005) // false
  • /^[2][0-9]{3}?$/.test(20052) // false

匹配日期中的所有汉字 并替换为-

var str = "2019年12月24日";
var s1 =str.replace(/[\u4E00-\u9FA5]/g,'-');
console.log(s1); //2019-12-24-
s1.substr(0,s1.length-2); //2019-12-24

验证手机号 vant

:rules="[
  { required: true, message: '请填写您的手机号码!' },
  { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式错误!'}
]"

匹配6位数字验证码

^/d{6}$ 或者 /d{6}

  • /^\d{6}$/.test('11111a') // false
  • /\d{6}/.test('111112') // false

匹配手机号中间四位*代替

'15600002865'.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2") // 156****2865

将手机号分隔为三份 空格隔开

  • /(\d{3})(\d{4})(\d{4})/g 12345678910 => 123 4567 8710
function fphone(value) {
    return value.replace(/(\d{3})(\d{4})(\d{4})/, "$1 $2 $3")
}
// vue中 实时更新文本框
computed: {
    fphone() {
        let _item
        if (this.phone.length > 7) {
            _item = String(this.phone).replace(/(\d{3})(\d{4})(\d{1})/, "$1 $2 $3")
        } else {
            _item = String(this.phone).replace(/(\d{3})(\d{1})/, "$1 $2")
        }
        return _item
    }
},

测试链接 常用正则

c.runoob.com/front-end/8…