在 AngularJS 中,我需要在输入电话号码时对其进行格式化。 我不想使用任何库,因为这应该很简单。
我需要的格式是:99 99 99 99 99
var phone = tel.replace(/\D*(\d{2})\D*(\d{2})\D*(\d{2})\D*(\d{2})\D*(\d{2})\D*/, '$1 $2 $3 $4 $5');
但这只会在我的号码完全输入后格式化我的号码。当数字尚未完成时,如何使此正则表达式起作用?
然后我尝试了这个:
var phone = tel.replace(/\D*(\d{2})\D*(\d{0,2})?\D*(\d{0,2})?\D*(\d{0,2})?\D*(\d{0,2})?\D*/, '$1 $2 $3 $4 $5');
但这显然是在添加不需要的空格。
最佳答案
你说你希望它“直截了当”,但你人为地限制了问题(通过强制解决方案只是正则表达式),而纯正则表达式实际上是解决这个问题的糟糕解决方案。
为什么?因为您的问题涉及有条件地向输出(空格)添加新字符,这些字符可能不会出现在输入中,但不应始终添加 - .replace()
无法处理该问题.
您最好结合使用正则表达式和其他 JavaScript 来处理条件格式:
// Get only the digits from the string
var phoneDigits = tel.replace(/\D/g, "");
// Join together the first up-to-5 pairs of digits with spaces,
// allowing for a singleton if the number of digits is odd.
var phone = (phoneDigits.match(/\d\d?/g) || []).slice(0,5).join(" ");
(|| []
位避免了当没有数字出现时匹配返回 null
的情况。)
关于javascript - 正则表达式电话号码实时格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30560385/