I have the following function in JavaScript, which takes in text for a USA phone number, tests against it to make sure nothing invalid is inputted, then formats it for display in the same text box.
It works well, but it needs to also accept phone extensions. The phone extension basically needs to pass through as is, so it can be any number of any characters, whether it begins with a space, a *, a ext, whatever the case is. I was asked not to worry about all of those cases, and as I said, to have the extension just pass through. I told my boss that we could just have another text box for the extension, but that isn't what he wants.
So, writing the regex for n number of any characters isn't difficult, the part I am more concerned about is how to grab these characters in the code that actually does the phone number formatting.
I'd guess I can just grab the characters after the valid phone number, but I'm honestly not sure how to do this, keeping in mind that the phone number is regex checked and the input may have had differing lengths. Any thoughts?
I would be grateful for any help! Here is the current code, which needs to be adjusted for accepting and returning the extension when it formats the phone number, keeping in mind the requirement that the extension can be any number of any characters:
function formatPhone(phoneObj) {
var phoneStr = phoneObj.value,
s2 = (""+phoneStr).replace(/\D/g, ''),
m = s2.match(/^(\d{3})?[- ]??[\s]?(\d{3})?[\s]?(\d{4})$/);
phoneObj.value = (!m) ? null : "(" + m[1] + ") " + m[2] + "-" + m[3];
}