Previous Page
Next Page

Formatting and Sorting Strings

Another typical task you might want to do is to sort a group of names. Script 8.6 combines the previous two examples and adds a sort. The end result is the list of names in last-name order, properly capitalized, and alphabetized.

Script 8.6. This script takes a bunch of names in any format and order and turns them into a neat and orderly list.

window.onload = initForms;

function initForms() {
     for (var i=0; i< document.forms.length; i++) {
        document.forms[i].onsubmit = function() {return validForm();}
     }
}

function validForm() {
     var allTags = document.getElementsByTagName("*");

     for (var i=0; i<allTags.length; i++) {
        validTag(allTags[i]);
     }
     return false;

     function validTag(thisTag) {
        var allClasses = thisTag.className.split(" ");

        for (var j=0; j<allClasses.length; j++) {
           validBasedOnClass(allClasses[j]);
        }

        function validBasedOnClass(thisClass) {
           switch(thisClass) {
              case "":
                 break;
              case "nameList":
                 thisTag.value = nameList(thisTag.value);
              default:
           }
        }

          function nameList(inNameList) {
             var newNames = new Array;
             var newNameField = "";

             var re = /\s*\n\s*/;
             var nameList = inNameList.split(re);

             re = /^(\S)(\S+)\s(\S)(\S+)$/;

             for (var k=0; k<nameList.length; k++) {
                if (nameList[k]) {
                   re.exec(nameList[k]);
                   newNames[k] = RegExp.$3. toUpperCase() + RegExp.$4. toLowerCase() + ", 
" +  RegExp.$1.toUpperCase() +  RegExp.$2.toLowerCase();
                }
             }

             newNames.sort();
             for (k=0; k<newNames.length; k++) {
                newNameField += newNames[k] + "\n";
             }
             return newNameField;
          }
      }
}

To format and sort strings:

1.
newNames[k] = RegExp.$3. toUpperCase() + RegExp.$4. toLowerCase() + ", " + RegExp.$1.
 toUpperCase() + RegExp.$2. toLowerCase();



In this example, we want to sort by last name, so we create the new newNames array by appending the uppercased first letter of the last name, the lowercased remainder of the last name, a comma and space, the uppercased first letter of the first name, and the lowercased remainder of the first name.

2.
newNames.sort();



The array method sort() sorts the elements of an array in place, overwriting the previous contents. Figure 8.9 shows the "before" version and Figure 8.10 the "after" version.

Figure 8.9. Here's the version as the user entered it.


Figure 8.10. And here's the sorted and cleaned up list, just the way we want it.



Previous Page
Next Page