I think you are going wrong on this. First of all, trying to hide an input error this way is a bad idea. If the user needs to enter a number and they add an extra dot, which tells you which one is good and which is bad? You better tell the user that something is wrong with their input.
But usually you use a regex to indicate what it should look like. And what are the substantial portions that you want to use with capture groups.
This is a capture group: ([a-z0-9])@example.com ; this is a group without capture: (?:hello|hi) .
In the case of a phone number, all that matters is the numbers, so you can capture them and take several forms between the characters. Here's a simple zip code:
([AZ][0-9][AZ]) ?([0-9][AZ][0-9])
Then all you have to do is join the captured groups. If they are present, the space will not be recorded.
Find more examples on MDN .
source share