SitePoint Sponsor

User Tag List

Results 1 to 7 of 7
  1. #1
    SitePoint Member
    Join Date
    Sep 2010
    Posts
    9
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Reformat Phone Numbers

    Hi everyone,

    I'm looking for a script that will reformat phone numbers into a more readable format. And I don't mean phone numbers that are entered into form fields. I mean just phone numbers that are a part of whatever page I happen to be viewing.

    For instance, the script would search a page and find a string of numbers like this: 9546302299

    It would then reformat the numbers and replace them. The end result would be this: (954) 630-2299

    I've figured that this regex is a piece of the puzzle, but I don't know enough about javascript to finish the script.

    Replace (/([\d]{3})([\d]{3})([\d]{4})/g with ($1) $2-$3

    It seems like a fairly simple script, but I can't for the life of me find one that's already available. Can anyone help me?

  2. #2
    SitePoint Addict
    Join Date
    Nov 2008
    Location
    Shropshire, England
    Posts
    274
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hope this helps

    Code JavaScript:
    var num ="9546302299";
     
    // A regular expression literal.
    var reg = /^(\d{3})(\d{3})(\d{4})/
     
    // Sequence put into an array
    var seq = [3,3,4];
    // The same as reg1, but this time using a new Regular Expression object. 
    // This way we can build a customized regular expression.
    var reg2 = new RegExp('^(\\d{'+seq[0]+'})(\\d{'+seq[1]+'})(\\d{'+seq[2]+'})');
     
    // 'a' is the complete match. n1,n2 and n3 are backrefences n1(..) n2(..) n3(..)
    var phoneNum = num.replace(reg2, function(a, n1, n2, n3){return "("+n1+") "+n2+"-"+n3;});
     
    console.log(phoneNum); // (954) 630-2299

    I'm guessing you will also need to 'walk the dom'.

    RLM

  3. #3
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,608
    Mentioned
    24 Post(s)
    Tagged
    1 Thread(s)
    One thing you need to remember is that most of the world's phone numbers do not fit that format.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  4. #4
    SitePoint Addict
    Join Date
    Nov 2008
    Location
    Shropshire, England
    Posts
    274
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Need to remove the '^' at the beginning of the regex.
    var reg = /(\d{3})(\d{3})(\d{4})/

    One thing you need to remember is that most of the world's phone numbers do not fit that format.
    Fair point.

    For starters
    http://en.wikipedia.org/wiki/Local_c...ephone_numbers

    RLM

  5. #5
    SitePoint Addict
    Join Date
    Nov 2008
    Location
    Shropshire, England
    Posts
    274
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Just a rough idea.

    Code JavaScript:
    // ['Initial match', 'Pattern to grab from match', 'function to replace with']
    var matches = { 
      f1 : ["\\d{10}", "(\\d{3})(\\d{3})(\\d{4})", function(a, n1, n2, n3){return "("+n1+") "+n2+"-"+n3;}],
      f2 : ["\\d{11}", "(\\d{3})(\\d{4})(\\d{4})", function(a, n1, n2, n3){return n1+' - '+n2+' - '+n3;}]
    };
     
    var numberCheck = function(node, mtches){
     
      var result = [],
      regMtch = new RegExp(mtches[0]), // Initial match
      regRep = new RegExp(mtches[1]), // To replace pattern
      matchFn = mtches[2]; // With
     
      var check = function(text){
        var mtch = text.match(regMtch);
    	if (mtch) result.push(mtch[0].replace(regRep, matchFn));
      };
     
      (function walkDom(node){
    	if (node.nodeType === 3 && !/\n/.test(node.nodeValue)) check(node.nodeValue);
    	node = node.firstChild;
    	while (node){
    		walkDom(node);
    		node = node.nextSibling;
    	}
      }(node))
     
      return result;
    };

    Test:
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Num Check</title>
    </head>
    <body>
    <p>What are you planning to do with my number 9546302299?</p>
    <ul>
      <li>9546302299</li>
      <li>0207696969</li>
      <li>02082224444</li>
      <li>0208969669</li>
      <li>4596203922</li>
    </ul>
    <script type="text/javascript">
    // ['Initial match', 'Pattern to grab from match', 'function to replace with']
    var matches = { 
      f1 : ["\\d{10}", "(\\d{3})(\\d{3})(\\d{4})", function(a, n1, n2, n3){return "("+n1+") "+n2+"-"+n3;}],
      f2 : ["\\d{11}", "(\\d{3})(\\d{4})(\\d{4})", function(a, n1, n2, n3){return n1+' - '+n2+' - '+n3;}]
    };
    
    var numberCheck = function(node, mtches){
    
      var result = [],
      regMtch = new RegExp(mtches[0]), // Initial match
      regRep = new RegExp(mtches[1]), // To replace pattern
      matchFn = mtches[2]; // With
      
      var check = function(text){
        var mtch = text.match(regMtch);
    	if (mtch) result.push(mtch[0].replace(regRep, matchFn));
      };
      
      (function walkDom(node){
    	if (node.nodeType === 3 && !/\n/.test(node.nodeValue)) check(node.nodeValue);
    	node = node.firstChild;
    	while (node){
    		walkDom(node);
    		node = node.nextSibling;
    	}
      }(node))
      
      return result;
    };
    
    console.log(numberCheck(document, matches.f1)); 
    // ["(954) 630-2299", "(954) 630-2299", "(020) 769-6969", "(020) 822-2444", "(020) 896-9669", "(459) 620-3922"]
    
    </script>
    </body>
    </html>

  6. #6
    SitePoint Member
    Join Date
    Sep 2010
    Posts
    9
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the assistance.

    I gave the most recent script you posted a whirl but it doesn't seem to be formatting any of the phone numbers in the unordered list.

  7. #7
    SitePoint Addict
    Join Date
    Nov 2008
    Location
    Shropshire, England
    Posts
    274
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Have you got the firebug plug-in for firefox? or alternatively Chrome (press ctrl-shift-j)?

    You need that to see console.log's output.

    Otherwise change
    Code:
    console.log(numberCheck(document, matches.f1));
    to

    Code:
    alert(numberCheck(document, matches.f1));
    I've just copied the code from this page into notepad++ and excuted it and it runs fine in firefox, ie, safari and chrome.

    Edit: By the way it's just a rough to work from (possibly). For one you want it to work on pages you're viewing (not sure how you go about that) and two as Felgall pointed out number formats vary, so you may well have to ammend patterns or add new ones.

    RLM


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •