libphonenumber-js
Version:
A simpler (and smaller) rewrite of Google Android's popular libphonenumber library
95 lines (75 loc) • 2.76 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.extractCountryCallingCode = extractCountryCallingCode;
exports.matches_entirely = matches_entirely;
var _metadata = require('./metadata');
var _metadata2 = _interopRequireDefault(_metadata);
var _IDD = require('./IDD');
var _common = require('./common.constants');
var _parseIncompletePhoneNumber = require('./parseIncompletePhoneNumber');
var _parseIncompletePhoneNumber2 = _interopRequireDefault(_parseIncompletePhoneNumber);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Parses a formatted phone number
// and returns `{ countryCallingCode, number }`
// where `number` is just the "number" part
// which is left after extracting `countryCallingCode`
// and is not necessarily a "national (significant) number"
// and might as well contain national prefix.
//
function extractCountryCallingCode(number, country, metadata) {
number = (0, _parseIncompletePhoneNumber2.default)(number);
if (!number) {
return {};
}
// If this is not an international phone number,
// then don't extract country phone code.
if (number[0] !== '+') {
// Convert an "out-of-country" dialing phone number
// to a proper international phone number.
var numberWithoutIDD = (0, _IDD.stripIDDPrefix)(number, country, metadata);
// If an IDD prefix was stripped then
// convert the number to international one
// for subsequent parsing.
if (numberWithoutIDD && numberWithoutIDD !== number) {
number = '+' + numberWithoutIDD;
} else {
return { number: number };
}
}
// Fast abortion: country codes do not begin with a '0'
if (number[1] === '0') {
return {};
}
metadata = new _metadata2.default(metadata);
// The thing with country phone codes
// is that they are orthogonal to each other
// i.e. there's no such country phone code A
// for which country phone code B exists
// where B starts with A.
// Therefore, while scanning digits,
// if a valid country code is found,
// that means that it is the country code.
//
var i = 2;
while (i - 1 <= _common.MAX_LENGTH_COUNTRY_CODE && i <= number.length) {
var countryCallingCode = number.slice(1, i);
if (metadata.countryCallingCodes()[countryCallingCode]) {
return {
countryCallingCode: countryCallingCode,
number: number.slice(i)
};
}
i++;
}
return {};
}
// Checks whether the entire input sequence can be matched
// against the regular expression.
function matches_entirely() {
var text = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var regular_expression = arguments[1];
return new RegExp('^(?:' + regular_expression + ')$').test(text);
}
//# sourceMappingURL=common.js.map