How to use regular expressions to achieve the effect of automatically adding spaces after every 4 bits of a string
This article introduces how to use regular expressions to achieve the effect of automatically adding spaces after every 4 digits of a string. The content is very detailed. Interested friends can refer to it for reference. I hope it can help you.
Method 1: Monitor the keyup event of the input box. When the length of the value value is 4, 8, 12, 16, insert the blank string " "(the code fragment in vue is as follows).
bankCardKeyup (e) { let self = this //if delete key, no spaces added and spaces removed from string ends 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 && value.length 12 && 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) { //call identify bank card function} 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) } } },
Method 2: Best Practice- - -Use regular matching to automatically set the value of the input box (you can add any character at any position, and automatically delete the space at the end of the string)
bankCardKeyup () { let self = this self.bankCard = self.bankCard.replace(/\s/g,'').replace(/[^\d]/g,'').replace(/(\d{4})(?=\ d)/g,'$1')} About how to use regular expressions to achieve the effect of automatically adding spaces after every 4 digits of a string, I hope the above content can be of some help to everyone and learn more. If you think the article is good, you can share it so that more people can see it.