Phone Number Parser

[Total: 0    Average: 0/5]

This code will determine the three main parts of a phone number.

Head Code:

<script>
function detectPN()
{
  /*
   * First get the object of the form "f1"->_f
   * Then get the "_string" to manipulate from the form object "start"
   */
  var _f=document.f1;
  var _string=_f.start.value;

  /*
   * Determine if all the () and " " and "-" are in the string.
   * Better job could be done here to validate the number is correct format.
   */
  if(_string.indexOf("(")==-1 ||
     _string.indexOf(")")==-1 ||
     _string.indexOf(" ")==-1 ||
     _string.indexOf("-")==-1)
  {
    /*
     * If not correct, show the user some feedback...
     */
    _f.area.value="?";
    _f.pre.value="?";
    _f.suf.value="?";
  }
  else /* else it must be a valid formatted phone number */
  {
    /*
     * Split the phone number around the space into
     * 2 array spots: "(###)" and "###-####"
     */
    var _temp=_string.split(" ");

    /*
     * Go get the Area Code from the first "(###)"
     * as index spots 1-4:
     * (###)
     * 01234
     */
    var _areaCode=_temp[0].substring(1,4);

    /*
     * Go split the 2nd half into 2 parts around the "-"
     */
    var _prefix=_temp[1].split("-")[0];
    var _suffix=_temp[1].split("-")[1];

    /*
     * Store the results in the form.
     */
    _f.area.value=_areaCode;
    _f.pre.value=_prefix;
    _f.suf.value=_suffix;
  }
}
</script>

Body Code:

<form name=f1>
Start:<input name=start value="(123) 456-7890"><BR>
<input type=button value="detect phone number" onclick="detectPN()"><BR>
Area:<input name=area><BR>
Pre:<input name=pre><BR>
Suf:<input name=suf><BR>
</form>

Times Viewed: 4

Leave a Reply

Your email address will not be published. Required fields are marked *