A little snippet to normalize an input phone number into a consistent international format, without blank spaces and leading zeroes. Any number without leading + is assumed to be domestic.
Replace internationalCode in row 2 with the country code of your region (e.g. ‘+1’ for the US).
private static String normalizePhone(String inputPhone){
String internationalCode = '+356'; // Replace with your country code
if(String.isNotBlank(inputPhone)){
// Check if the original input starts with +
Boolean startsWithPlus = inputPhone.startsWith('+');
// Remove non-numeric input
String notNumbers = '[^0-9]';
inputPhone = inputPhone.replaceAll(notNumbers, '');
// Remove leading zeroes and plus
inputPhone = inputPhone.replaceFirst('^0+', '');
// Add International Code to numbers without originally leading +
inputPhone = startsWithPlus ? ('+' + inputPhone) : (internationalCode + inputPhone);
}
return inputPhone;
}