Regular expressions aren’t exactly my strong suit. I got a regex for validating international phone numbers here. The validation bit works for me but I don’t understand how I can take the regex result and use it to format the number. My question is how do I figure out, from the regex, what the groupings are that I can use to display?
var intl1RegexObj = /^((\+)?[1-9]{1,2})?([-\s\.])?((\(\d{1,4}\))|\d{1,4})(([-\s\.])?[0-9]{1,12}){1,2}$/;
if (IntlRegexObj.test(businessPhoneValue))
{
var formattedPhoneNumber = businessPhoneValue.replace(IntlRegexObj, "($1)");
// display formatted result
}
After simplifying that mess of a regex:
There are now only 3 capturing groups.
First one
$1is easy, the country code with an optional +.Then you have the local area code, basically 1-4 numbers with / without parentheses optionally prefixed by
[-\s.]. That’s$2Finally you have your the actual phone number which can be from 1 to 24 numbers, including optional space or dot or minus sign
[-\s.]More detailed explanation: