function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
GailGail 

Find area code of a phone number?

I need to extract the area code from the Account Phone field. Luckily, I really only need the data on North American accounts, so I'm thinking I could remove all non-number fields and then extract characters depending on what it starts with (if 011, then char 4 to 6, if 1, then char 2 to 4, else char 1 to 3). That would catch most cases but I can't believe there isn't code already out there for doing this. I've been searching all over to no avail. Are there functions I'm unaware of that could help? Anyone know of a better way to do this? 

Best Answer chosen by Admin (Salesforce Developers) 
SLockardSLockard

Hi, here is some code that I think will get you on your way, good luck.

 

String original = '(011) 555-0123';
String numericData = original.replaceAll('[^0-9]', '');
String nonNumericData = '';
nonNumericData = original.replaceAll('[0-9]', '');

system.debug('Non Numeric = ' + nonNumericData);
system.debug('Numeric = ' + numericData);

String areaCode = numericData.substring(0,3);
system.debug('Area Code = ' + areaCode);

if (areaCode == '011')
{
 	// logic
}
else
{
    // more logic
}

 

All Answers

SLockardSLockard

Hi, here is some code that I think will get you on your way, good luck.

 

String original = '(011) 555-0123';
String numericData = original.replaceAll('[^0-9]', '');
String nonNumericData = '';
nonNumericData = original.replaceAll('[0-9]', '');

system.debug('Non Numeric = ' + nonNumericData);
system.debug('Numeric = ' + numericData);

String areaCode = numericData.substring(0,3);
system.debug('Area Code = ' + areaCode);

if (areaCode == '011')
{
 	// logic
}
else
{
    // more logic
}

 

This was selected as the best answer
GailGail

Thanks SLockard!