If a formatted phone number is an international one then it strips the `+${country_phone_code}` prefix from the formatted number.
12336
function strip_country_phone_code(formatted_number, metadata)
{
	if (!formatted_number || formatted_number[0] !== '+' || formatted_number === '+')
	{
		return formatted_number
	}

	for (const country_phone_code of Object.keys(metadata.country_phone_code_to_countries))
	{
		if (formatted_number.indexOf(country_phone_code) === '+'.length)
		{
			return formatted_number.slice('+'.length + country_phone_code.length).trim()
		}
	}

	return formatted_number
}
317668
function isValid(number, countryCode) {
    try {
        var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance();
        var numberObj = phoneUtil.parseAndKeepRawInput(number, countryCode);
        return phoneUtil.isValidNumber(numberObj);
    } catch (e) {
        return false;
    }
}
1159089
protected function rawInputContainsNationalPrefix($rawInput, $nationalPrefix, $regionCode)
    {
        $normalizedNationalNumber = static::normalizeDigitsOnly($rawInput);
        if (strpos($normalizedNationalNumber, $nationalPrefix) === 0) {
            try {
                // Some Japanese numbers (e.g. 00777123) might be mistaken to contain the national prefix
                // when written without it (e.g. 0777123) if we just do prefix matching. To tackle that, we
                // check the validity of the number if the assumed national prefix is removed (777123 won't
                // be valid in Japan).
                return $this->isValidNumber(
                    $this->parse(substr($normalizedNationalNumber, mb_strlen($nationalPrefix)), $regionCode)
                );
            } catch (NumberParseException $e) {
                return false;
            }
        }
        return false;
    }
1184839
public static function formatPhone($phone)
    {
        $ddd = '';
        $phone = self::keepOnlyNumbers($phone);

        // removes leading zero
        if (substr($phone, 0, 1) == 0) {
            $phone = substr($phone, 1);
        }

        // verifies if have ddd
        if (strlen($phone) > 9) {    
            //removes country identifier
            if (strlen($phone) > 11) {
                $phone = substr($phone, 2);
            }
            $ddd = substr($phone, 0, 2);
            $phone = substr($phone, 2);
        }

        return ['areaCode' => $ddd, 'number' => $phone];
    }
418765
function unPrefix(s, prefix) {
  s = str(s);
  if (!prefix) return s;
  if (s.slice(0, prefix.length) === prefix) return s.slice(prefix.length);
  return s;
}
369907
function normalize_country_code(country, dictionary)
{
	// Normalize `country` if it's an empty string
	if (country === '')
	{
		country = undefined
	}

	// No country is selected ("International")
	if (country === undefined || country === null)
	{
		return country
	}

	// Check that `country` code exists
	if (dictionary[country] || default_dictionary[country])
	{
		return country
	}

	throw new Error(`Unknown country: "${country}"`)
}
548968
def parse_country(phone, country)
      data = Phonelib.phone_data[country]
      return nil unless data

      # if country was provided and it's a valid country, trying to
      # create e164 representation of phone number,
      # kind of normalization for parsing
      e164 = convert_to_e164 with_replaced_national_prefix(phone, data), data
      # if phone starts with international prefix of provided
      # country try to reanalyze without international prefix for
      # all countries
      return analyze(e164[1..-1], nil) if Core::PLUS_SIGN == e164[0]
      # trying to parse number for provided country
      parse_single_country e164, data
    end
818329
function formatInput(val, countryCode, addSuffix, allowExtension, isAllowedKey) {
    try {
        var clean = val.replace(/\D/g, ""),
            // NOTE: we use AsYouTypeFormatter because the default format function can't handle incomplete numbers e.g. "+17024" formats to "+1 7024" as opposed to "+1 702-4"
            formatter = new i18n.phonenumbers.AsYouTypeFormatter(countryCode),
            // if clean is empty, we still need this to be a string otherwise we get errors later
            result = "",
            next,
            extSuffix = " ext. ";

        if (val.substr(0, 1) == "+") {
            clean = "+" + clean;
        }

        for (var i = 0; i < clean.length; i++) {
            // TODO: improve this so don't just pump in every digit every time - we should just cache this formatter object, and just call inputDigit once each time the user enters a new digit
            next = formatter.inputDigit(clean.charAt(i));
            // if adding this char didn't change the length, or made it smaller (and there's no longer any spaces): that means that formatting failed which means the number was no longer a potentially valid number, so if we're allowing extensions: assume the rest is the ext
            if (allowExtension && result && next.length <= result.length && next.indexOf(" ") == -1) {
                // set flag for extension
                next = -1;
                break;
            }
            result = next;
        }

        // for some reason libphonenumber formats "+44" to "+44 ", but doesn't do the same with "+1"
        if (result.charAt(result.length - 1) == " ") {
            result = result.substr(0, result.length - 1);
        }
        // check if there's a suffix to add (unless there's an ext)
        if (addSuffix && !val.split(extSuffix)[1]) {
            // hack to get formatting suffix
            var test = formatter.inputDigit('5');
            // again the "+44 " problem... (also affects "+45" apparently)
            if (test.charAt(test.length - 1) == " ") {
                test = test.substr(0, test.length - 1);
            }
            // if adding a '5' introduces a formatting char - check if the penultimate char is not-a-number
            var penultimate = test.substr(test.length - 2, 1);
            // Note: never use isNaN without parseFloat
            if (isNaN(parseFloat(penultimate))) {
                // return the new value (minus that last '5' we just added)
                return test.substr(0, test.length - 1);
            } else if (allowExtension && result && test.length <= result.length && test.indexOf(" ") == -1 && !isAllowedKey) {
                // else if the next digit would break the formating, and we're allowing extensions, AND this is not an allowed key: add the suffix
                // NOTE: we must check this is not an allowed key because if it was that means it was the last digit in a valid number and we dont want to add the "ext" suffix in that case. This whole condition is just here to catch the case that: after typing a valid number, they try to type "ext" - this will not automatically add it for them.
                return result + extSuffix;
            }
        }

        // if the clean number contains an extension we need to add it
        if (next == -1) {
            result += extSuffix + clean.substring(i, clean.length);
        }

        return result;
    } catch (e) {
        return val;
    }
}
1049121
private static int parseCountryCode(String countryCode) {

    String normalized = countryCode;
    if (normalized.startsWith(InternationalCallPrefix.PREFIX_PLUS)) {
      normalized = normalized.substring(1);
    } else if (normalized.startsWith(InternationalCallPrefix.PREFIX_00)) {
      normalized = normalized.substring(2);
    } else if (normalized.startsWith(InternationalCallPrefix.PREFIX_011)) {
      normalized = normalized.substring(3);
    }
    if (normalized.startsWith("0")) {
      throw new IllegalArgumentException(countryCode);
    }
    try {
      int cc = Integer.parseInt(normalized);
      return cc;
    } catch (NumberFormatException e) {
      throw new IllegalArgumentException(countryCode, e);
    }
  }
186179
function e164(value, country_code, metadata)
{
	if (!value)
	{
		return undefined
	}

	// If the phone number is being input in an international format
	if (value[0] === '+')
	{
		// If it's just the `+` sign
		if (value.length === 1)
		{
			return undefined
		}

		// If there are some digits, the `value` is returned as is
		return value
	}

	// For non-international phone number a country code is required
	if (!country_code)
	{
		return undefined
	}

	// The phone number is being input in a country-specific format

	const partial_national_number = parse_partial_number(value, country_code).national_number

	if (!partial_national_number)
	{
		return undefined
	}

	// The value is converted to international plaintext
	return format(partial_national_number, country_code, 'International_plaintext', metadata)
}
29924
function Phones(knwl) {
    
    this.languages = {
        'english': true,
    };

    this.areaCodeLength = 3; // Hard code this assumption for now
    
    // IMPORTANT: This function makes the assumption that there is always 3 digits in an area code
    this.formatPhoneNumber = function(number) {
        var formattedNumber = number.slice(number.length - 7, number.length - 4) + "-" +
        number.slice(number.length - 4, number.length);
    
        formattedNumber = "(" + number.slice(number.length - (phones.areaCodeLength + 7), number.length - 7) + ") " +
        formattedNumber;
    
        if (number.length > (phones.areaCodeLength + 7)) {
            formattedNumber = "+" + number.slice(0, number.length - (phones.areaCodeLength + 7)) +
            " " + formattedNumber;
        }
        return formattedNumber;
    };
    
    this.calls = function() {
        var results = [];
        
        var words = knwl.words.get('words');
        var currWord = null;
        
        /* Phone Numbers can be as little as 7 digits per word,
           and as large as 13 if the word contains country code & area code & phone number
           note: this applies to North American area codes assuming 3 digits
           and is not applicable globally */
           var phoneRegexp = /^\d{7,13}$/;
        // North American Area Code's always have 3 digits
        // To make this universal, could use a dictionary keyed on Country
        var areaCodeRegExp = /^\d{3}$/;
        // Country Code's vary from 1 to 3 digits
        var countryCodeRegExp = /^\d{1,3}$/;
    
        for (var i = 0; i < words.length; i++) {
            currWord = knwl.tasks.removeCharacters(["-", "(", ")"], words[i]);
    
            if (phoneRegexp.test(currWord)) {
                /* At this point the word is thought to be a phone number.
                   If the current word is only of length 7 it's required that the previous word
                   is the area code, assuming there is a previous word. */
                   if (i > 0 && currWord.length === 7) {
                    var areaCode = knwl.tasks.removeCharacters(["(", ")"], words[i - 1]);
                    if (areaCodeRegExp.test(areaCode)) {
                        currWord = areaCode + currWord;
    
                        /* At this point the current word and previous word make up the area code
                           and phone number.
                           Check whether the 2 words back represents the country code */
                           if (i > 1) {
                            var countryCode = knwl.tasks.removeCharacters("+", words[i - 2]);
                            if (countryCodeRegExp.test(countryCode)) {
                                currWord = countryCode + currWord;
                            }
                        }
                    }
                    /* If the current word is not length 7, it's possible that the current word contains
                   both the phone number and area code and the previous word is the country code.
                   Once again, this is assuming that the areaCode length is 3 */
               } else if (i > 0 && currWord.length === (phones.areaCodeLength + 7)) {
                var countryCode = knwl.tasks.removeCharacters("+", words[i - 1]);
                if (countryCodeRegExp.test(countryCode)) {
                    currWord = countryCode + currWord;
                }
            }
    
                /* We needed the phoneRegex to accept a minimum of 7 digits in case the preceding words
                   made up the area code and possibly the country code, but if at this point there is
                   not at least 7 digits plus the areaCodeLength in the currWord then it is not likely
                   a phone number */
                   if (currWord.length >= (7 + phones.areaCodeLength)) {
                    var phoneObj = {
                        phone: phones.formatPhoneNumber(currWord),
                        preview: knwl.tasks.preview(i),
                        found: i
                    };
                    results.push(phoneObj);
                }
            }
        }
        return results;
    };
    var phones = this;
}
1062041
private String formatPhoneNumber() {

    StringBuilder buffer = new StringBuilder();
    buffer.append(this.countryCode);
    buffer.append(' ');
    buffer.append(this.areaCode);
    buffer.append(' ');
    buffer.append(this.localNumber);
    if ((this.extension != null) && (this.extension.length() > 0)) {
      buffer.append('-');
      buffer.append(this.extension);
    }
    return buffer.toString();
  }
478961
private static String removeExplicitGlobalPrefix(String qname) {
    for (String global : GLOBAL_NAMES) {
      if (qname.startsWith(global)) {
        return qname.substring(global.length());
      }
    }
    return qname;
  }
992149
def e_164(msisdn: str) -> str:
    
    # Phonenumbers library requires the + to identify the country, so we add it if it
    # does not already exist
    number = phonenumbers.parse("+{}".format(msisdn.lstrip("+")), None)
    return phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.E164)
650774
def strip_prefix(string, prefix, regex=False):
    """"""
    if not isinstance(string, six.string_types) or not isinstance(prefix, six.string_types):
        msg = 'Arguments to strip_prefix must be string types. Are: {s}, {p}'\
              .format(s=type(string), p=type(prefix))
        raise TypeError(msg)

    if not regex:
        prefix = re.escape(prefix)
    if not prefix.startswith('^'):
        prefix = '^({s})'.format(s=prefix)
    return _strip(string, prefix)
832092
def convert_to_e164(phone, data)
      match = phone.match full_regex_for_data(data, Core::VALID_PATTERN, !original_starts_with_plus?)
      case
      when match
        "#{data[Core::COUNTRY_CODE]}#{match.to_a.last}"
      when phone.match(cr("^#{data[Core::INTERNATIONAL_PREFIX]}"))
        phone.sub(cr("^#{data[Core::INTERNATIONAL_PREFIX]}"), Core::PLUS_SIGN)
      when original_starts_with_plus? && phone.start_with?(data[Core::COUNTRY_CODE])
        phone
      else
        "#{data[Core::COUNTRY_CODE]}#{phone}"
      end
    end
1274206
def clean_text(self, country, guess=False, **kwargs):
        
        code = country.lower().strip()
        if code in self.names:
            return code
        country = countrynames.to_code(country, fuzzy=guess)
        if country is not None:
            return country.lower()