JavaScript code to find all phone numbers in a string and return them as a list

There are plenty of examples available of regular expressions that match phone numbers, even some that match multiple formats, but none of the example I could find could deal with strings containing multiple phone numbers. So I decided to write my own, and decided that I didn’t need to get into complex regular expressions a simple parse loop would suffice.

The principle behind this parser is that each phone number is comprised of digits, possibly with a + international prefix, and may include embedded spaces and other punctuation such as [().-]. The problem is how to recognise when one number ends and the next one starts when space is not only used to delimit numbers, but is also used as punctuation in the middle of a number.

This parse solves this by choosing a minimum valid number length (which can change for each number during the parse depending on the type of number detected), and collecting the digits of that number until either a non-number non-punctuation character is found (text or other punctuation) which definitely delimits a number or in the case of a space, if we have enough number to satisfy the minimum length, consider that number complete and start looking for the next.

The placeCall method can be used to trigger the browsers/os ‘tel:’ url scheme handler, for example a sip client, or on a mobile device, the actual dialer.

There is room for improvement, for example, currently the code presumes any number starting with a non-0 digit is a local number, and allows a much shorter minimum length so that it can pick up extension numbers, this is fine for the UK, but probably isn’t work in other countries.

var PhoneNumberParser = function() {

    var minimum = 9;            // typical minimum phone number length
    this.items = [];

    var public = PhoneNumberParser.prototype;
    public.parse = function(str) {
        var items = this.items = [];

        var i = 0, n = '', min = minimum;

        while(i < str.length) {
            switch(str[i]) {
            case '+':                                   // start of international number
                if (n.length >= min) items.push(n);
                n = str[i];
                min = minimum + 2;                      // at least 2 more chars in number
                break;
            case '-': case '.': case '(': case ')':     // ignore punctuation
                break;
            case ' ':
                if (n.length >= min) {              // space after consuming enough digits is end of number
                    items.push(n);
                    n = '';
                }
                break;
            default:
                if (str[i].match(/[0-9]/)) {            // add digit to number
                    n += str[i];
                    if (n.length == 1 && n != '0') {
                        min = 3;                        // local number (extension possibly)
                    }
                } else {
                    if (n.length >= min) {
                        items.push(n);                  // else end of number
                    }
                    n = '';
                }
                break;
            }
            i++;
        }

        if (n.length >= min) {              // EOF
            items.push(n);
        }
    }

    public.placeCall = function(i) {
        if (i < this.items.length) {
            var a = document.createElement("a");
            a.href = "tel:"+this.items[i];
            var e = document.createEvent('MouseEvents');
            e.initMouseEvent('click', true, true);
            a.dispatchEvent(e);
        }
    }
};

Example usage:

// parse a string for numbers
var numbers = new PhoneNumberParser();
numbers.parse("01234 567890 01 (234) 567890 +1 301 555 0100 800.555.6000");

// display the results
alert(numbers.items.length);
alert(numbers.items[0]);
alert(numbers.items[1]);
alert(numbers.items[2]);
alert(numbers.items[3]);

// make a call
numbers.placeCall(3);
Advertisements

About austinfrance

Technical Developer @ RedSky IT / Explorer Software
This entry was posted in JavaScript. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s