Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use regular expressions to achieve the effect of automatically adding spaces after every 4 bits of a string

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report