I'm trying to do phone masking using the example in this link, but without success.What I want to do is remove the parentheses and reorder.
Rule: the first character is always 5. In the form of 3 4 2 2, example: 532 123 45 67
Thanks in advance for your help.
const $input = document.querySelector('[data-js="input"]')
$input.addEventListener('input', handleInput, false)
function handleInput (e) {
e.target.value = phoneMask(e.target.value)
}
function phoneMask (phone) {
return phone.replace(/\D/g, '')
.replace(/^(\d)/, '($1')
.replace(/^(\(\d{3})(\d)/, '$1) $2')
.replace(/(\d{3})(\d)/, "$1-$2")
.replace(/(-\d{4})\d ?$/, '$1');
}
CodePudding user response:
There is an easier way :
1- Remove any non-number character
2- Format the numbers as "3 4 2 2" (or any other way)
phone = ' (123) 45678901';
phone = phone.replace(/[^0-9] /gim, '');
phone = phone.replace(/^([0-9]{3})([0-9]{4})([0-9]{2})([0-9]{2})$/, '$1 $2 $3 $4');
CodePudding user response:
Regex can be tricky but I love how nice is the result :)
function phoneMask (phone) {
return phone.replace(/\D/g, '')
.replace(/(^[^5])/, '')
.replace(/(\d{3})(\d)/, '$1 $2')
.replace(/(\d{4})(\d{1,2})/, '$1 $2')
.replace(/(\d{4}\s\d{2})(\d{1,2})/, '$1 $2')
.replace(/(\d{4}\s\d{2}\s\d{2})\d ?$/, '$1')
}
Explained steps:
- To only allow numbers, replace non-digits with empty string:
.replace(/\D/g, '')
- Allow only 5 at the beginning, so replace first digit which isn't 5 by empty string:
.replace(/(^[^5])/, '')
- Make 2 groups: the first with 3 digits and add a space between them:
.replace(/(\d{3})(\d)/, '$1 $2')
- Make new 2 groups: the first with 4 digits and the second with one or two digits and add a space between them. As the previous step grouped by 3, this step will affect only new digits:
.replace(/(\d{4})(\d{1,2})/, '$1 $2')
- Make others 2 groups: first one with 4-space-2-digits and second with one or two digits and add a space between them:
.replace(/(\d{4}\s\d{2})(\d{1,2})/, '$1 $2')
- To prevent adding more digits, after the sequence 4-space-2-space-2-digits is completed, end string:
.replace(/(\d{4}\s\d{2}\s\d{2})\d ?$/, '$1')