正则的几种常见校验

1:适用于表单里面的手机号,密码的校验

//手机号:
/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
//密码:1-6数字:
 /^\d{6}$/

2:格式化货币的校验

(校验是从.符号开始向前面数3位进行逗号分隔),可以根据需求去改{num}的值   

   const num = '123456789'
    const num2 = '123456789.123'
    const num3 = '1234'
    const num4 = '1234.123333'
    const formtmoney = (money) => {
      return money.replace(new RegExp(`(?!^)(?=(\\d{3})+${money.includes('.') ? '\\.' : '$'})`, 'g'), ',')
    }
    //从.开始向前面数3位进行逗号分隔
    console.log(formtmoney(num))  //123,456,789
    console.log(formtmoney(num2))//123,456,789.123
    console.log(formtmoney(num3))//1,234
    console.log(formtmoney(num4))//1,234.123333

3:实现trim功能(去除空格)注:可以去除前后空格,不可以去除字符串中间空格

   const string = '    hellow'
    const string1 = '   h  e l  l  o   w   '
    const string2 = 'hellow    '
    const trims = (str) => {
      return str.replace(/^\s*|\s*$/g, '')
    }
    //可以去除前后空格,不可以去除字符串中间空格
    console.log(trims(string))//hellow
    console.log(trims(string1))//h  e l  l  o   w
    console.log(trims(string2))//hellow

4:对电话的分隔(分隔电话 3-4-4)

    let mobileReg = new RegExp(/(?=(\d{4})+$)/g)
    let mobile = '13912345678'
    console.log(mobile.replace(mobileReg, '-'))//139-1234-5678

5:检查是http:还是https:

    let checkProtocol = new RegExp(/^http?:/)
    let url1 = 'https://xd.git/dist/vue/index.html?name=zhangshan&age=100'
    let url = 'http://xd.git/dist/vue/index.html?name=zhangshan&age=100'
    console.log(checkProtocol.test(url1))//fasle
    console.log(checkProtocol.test(url))//true

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农夫_山泉水

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值