I'm attempting to automatically insert a hyphen (-) in between 10 digits of a phone number as it is being typed into the text field, following North American standard formatting. I want the output to look like this: 647-364-3975
I am using the keyup event with TypeScript to achieve this. The way it works is that the hyphen (-) is added after typing all ten digits of the phone number.
<input id="PhoneNumberInputField"
(keyup)="_phoneNumberInputKeyUp($event)" [(ngModel)]="sharedVariables.PhoneNumberInput" maxlength="10" />
_phoneNumberInputKeyUp(event: any) {
var value = this.sharedVariables.PhoneNumberInput
if(value.length > 0){
var formatted = value.replace(/^(\d{3})(\d{3})(\d{4}).*/,"$1-$2-$3");
this.sharedVariables.PhoneNumberInput = formatted;
}
}