For my AngularJS project, I am looking to format phone numbers as they are being typed, without relying on any external library.
The desired format is: 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');
The issue I encountered is that the regular expression only formats the number once it has been fully typed. Is there a way to make it work while the number is still being entered?
I attempted a modified version of the regular expression:
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');
However, this resulted in unnecessary additional spaces being added. Any suggestions on how to improve the regex?