How can I check a phone number and bring it back to normal with a regular expression?
-
Hello everyone.
Faced a problem while trying to bring the phone number back to normal.
Wrote the following function:
function prettifyNumber(inputVal) { const prettified = inputVal .replace(/\D/g, "") .replace(/^7|^8/, "") .replace(/(\d{3})(\d{3})(\d{2})(\d{2})/, "+7 ($1) $2-$3-$4"); return prettified.length === 18 ? prettified : inputVal; }
When checking regular numbers, the function works fine, but when you try to check the number "+7 (495) 111-22-2x" (you can substitute any non-number character instead of v), the value is returned as if it were a valid number.
Why is this happening, given that the very first replace should remove all non-numeric characters?JavaScript Autumn Caldwell, Nov 10, 2020 -
return prettified.length === 18 ? prettified : inputVal;
it returns not "as if it were a real number", but the function argument, that is, what you fed him, then back and givesAnonymous
1 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!