正则表达式实现字符串每4位后自动加空格效果(两种方法)
需求:输入框中输入银行卡号(或其他)时,每4位自动加空格(如下图)
分析
方法一:监控输入框的keyup事件,当value值的长度为4,8,12,16时,插入空格字符串“ ”(vue中代码片段如下)
<input type="text" v-model="bankCard" @keyup="bankCardKeyup"> bankCardKeyup (e) { let self = this // 如果是删除键,则不加空格,且删去字符串末端空格 if (e.keyCode === 8) { self.bankCard = self.bankCard.replace(/[\s\n\t]+$/g, "") return } self.bankCard = self.bankCard.replace(/[^0-9|' ']*/g, '') let value = self.bankCard.replace(/[^0-9]*/g, '') if (value.length > 4 && value.length <= 8) { self.bankCard = value.slice(0, 4) + ' ' + value.slice(4, value.length) } else if (value.length > 8 && value.length <= 12) { self.bankCard = value.slice(0, 4) + ' ' + value.slice(4, 8) + ' ' + value.slice(8, value.length) } else if (value.length > 12 && value.length <= 16) { self.bankCard = value.slice(0, 4) + ' ' + value.slice(4, 8) + ' ' + value.slice(8, 12) + ' ' + value.slice(12, value.length) if (value.length === 16) { // 调用识别银行卡函数 } } else if (value.length > 16) { self.bankCard = value.slice(0, 4) + ' ' + value.slice(4, 8) + ' ' + value.slice(8, 12)+ ' ' + value.slice(12, 16) + ' ' + value.slice(16, value.length) if (value.length === 19) { // 调用识别银行卡函数 } else if (value.length > 19) { self.bankCard = value.slice(0, 4) + ' ' + value.slice(4, 8) + ' ' + value.slice(8, 12)+ ' ' + value.slice(12, 16) + ' ' + value.slice(16, 19) } } },
方法二:最佳实践 - - - 利用正则匹配,自动设置input框的value值(能在任意位置添加任意字符,且会自动删除字符串末端空格)
<input type="text" v-model="bankCard" @keyup="bankCardKeyup"> bankCardKeyup () { let self = this self.bankCard = self.bankCard.replace(/\s/g,'').replace(/[^\d]/g,'').replace(/(\d{4})(?=\d)/g,'$1 ') }
总结
相关推荐
liusarazhang 2020-06-14
wangzhaotongalex 2020-10-20
wyq 2020-11-11
TLROJE 2020-10-26
风雨断肠人 2020-10-13
duanqingfeng 2020-09-29
rechanel 2020-11-16
cshanzhizi 2020-10-16
luofuIT成长记录 2020-09-22
phphub 2020-09-10
taomengxing 2020-09-07
MaggieRose 2020-08-19
flyingssky 2020-08-18
山水沐光 2020-08-18
jyj00 2020-08-15
AHuqihua 2020-08-09
山水沐光 2020-08-03