UNPKG

2.71 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports["default"] = parseIncompletePhoneNumber;
7exports.parsePhoneNumberCharacter = parsePhoneNumberCharacter;
8
9var _parseDigits = require("./helpers/parseDigits");
10
11/**
12 * Parses phone number characters from a string.
13 * Drops all punctuation leaving only digits and the leading `+` sign (if any).
14 * Also converts wide-ascii and arabic-indic numerals to conventional numerals.
15 * E.g. in Iraq they don't write `+442323234` but rather `+٤٤٢٣٢٣٢٣٤`.
16 * @param {string} string
17 * @return {string}
18 * @example
19 * ```js
20 * // Outputs '8800555'.
21 * parseIncompletePhoneNumber('8 (800) 555')
22 * // Outputs '+7800555'.
23 * parseIncompletePhoneNumber('+7 800 555')
24 * ```
25 */
26function parseIncompletePhoneNumber(string) {
27 var result = ''; // Using `.split('')` here instead of normal `for ... of`
28 // because the importing application doesn't neccessarily include an ES6 polyfill.
29 // The `.split('')` approach discards "exotic" UTF-8 characters
30 // (the ones consisting of four bytes) but digits
31 // (including non-European ones) don't fall into that range
32 // so such "exotic" characters would be discarded anyway.
33
34 for (var _iterator = string.split(''), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
35 var _ref;
36
37 if (_isArray) {
38 if (_i >= _iterator.length) break;
39 _ref = _iterator[_i++];
40 } else {
41 _i = _iterator.next();
42 if (_i.done) break;
43 _ref = _i.value;
44 }
45
46 var character = _ref;
47 result += parsePhoneNumberCharacter(character, result) || '';
48 }
49
50 return result;
51}
52/**
53 * Parses next character while parsing phone number digits (including a `+`)
54 * from text: discards everything except `+` and digits, and `+` is only allowed
55 * at the start of a phone number.
56 * For example, is used in `react-phone-number-input` where it uses
57 * [`input-format`](https://gitlab.com/catamphetamine/input-format).
58 * @param {string} character - Yet another character from raw input string.
59 * @param {string?} prevParsedCharacters - Previous parsed characters.
60 * @param {object} meta - Optional custom use-case-specific metadata.
61 * @return {string?} The parsed character.
62 */
63
64
65function parsePhoneNumberCharacter(character, prevParsedCharacters) {
66 // Only allow a leading `+`.
67 if (character === '+') {
68 // If this `+` is not the first parsed character
69 // then discard it.
70 if (prevParsedCharacters) {
71 return;
72 }
73
74 return '+';
75 } // Allow digits.
76
77
78 return (0, _parseDigits.parseDigit)(character);
79}
80//# sourceMappingURL=parseIncompletePhoneNumber.js.map
\No newline at end of file