Previous Page
Next Page

Formatting Strings

Those darn users often enter data in a haphazard fashion. If you want entries to follow a standard format, your best bet is to handle the formatting yourself. Script 8.5 shows how to take a list of names and convert them to standard capitalization format.

Script 8.5. This script takes a name entered in any format and replaces it with the capitalization you desire.

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.$1. toUpperCase() + RegExp.$2. toLowerCase() + " 
" + RegExp.$3.toUpperCase() + RegExp.$4.toLowerCase();
                 }
              }

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

To format a string:

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



This regular expression again expects to find names in first name, space, last name order, and separates each name into four parts: the first letter of the first name ^(\S), the remainder of the first name (\S+), the first letter of the last name (\S), and the remainder of the last name (\S+)$. Note that the ^ and $ force the string to begin at the beginning and end at the endingwe don't want to leave any parts out.

2.
for (var k=0; k<nameList.length; k++) {



We want to look at each name in the nameList array, shown in Figure 8.7.

Figure 8.7. Here's the before version of the names.


3.
re.exec(nameList[k]);



This step uses the exec() method to execute the re pattern on the string nameList[k], breaking the string into four parts and automatically setting JavaScript's built-in RegExp object. These four parts will be stored in RegExp.$1, RegExp.$2, RegExp.$3, and RegExp.$4 (respectively).

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



The new version of the name is stored in the newNames array. It consists of the first letter of the first name (RegExp.$1), forced to uppercase, then the remainder of the first name (RegExp.$2) forced to lowercase, then a space, then the first letter of the last name (RegExp.$3) forced to uppercase, and finally the remainder of the last name (RegExp.$4) forced to lowercase. The name is then displayed, as shown in Figure 8.8.

Figure 8.8. And here's how they look afterwards, just the way we wanted them.


About the RegExp Object

JavaScript has a built-in RegExp object that's automatically set (and reset) every time a script executes a regular expression method (given in Tables 8.4 and 8.5). The properties of this object are shown in Table 8.3 and its methods in Table 8.4. The RegExp object isn't a variable that contains the result of the regular expression operation, but rather it contains the pattern described by the regular expression, in a form that can be used in your scripts via the RegExp object's properties and methods.

Table 8.3. Properties of the RegExp Object

Properties

Meaning

$1 (tHRough $9)

Parenthesized substring matches

$_

Same as input

$*

Same as multiline

$&

Same as lastMatch

$+

Same as lastParen

$'

Same as leftContext

$'

Same as rightContext

constructor

Specifies the function that creates an object's prototype

global

Search globally (g modifier in use)

ignoreCase

Search case-insensitive (i modifier in use)

input

The string to search if no string is passed

lastIndex

The index at which to start the next match

lastMatch

The last matched characters

lastParen

The last parenthesized substring match

leftContext

The substring to the left of the most recent match

multiline

Whether strings are searched across multiple lines

prototype

Allows the addition of properties to all objects

rightContext

The substring to the right of the most recent match

source

The regular expression pattern itself


Table 8.4. Methods of the RegExp Object

Methods

Meaning

compile(pattern,[, "g" | "i" | "gi"])

Compiles a regular expression

exec(string)

Executes a search for a match

test(string)

Tests for a match

toSource()

Returns a literal representing the object

toString()

Returns a string representing the specified object

valueOf()

Returns the primitive value of the specified object


Table 8.5. String Methods

Methods

Meaning

match(re)

Finds a match for a regular expression pattern (re) within a string

replace(re,replaceStr)

Using the regular expression (re), performs the desired replacement

search(re)

Searches for a match to the regular expression (re)

split(re)

Splits a string based on a regular expression (re)




Previous Page
Next Page