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