String validation isn't the only useful thing you can do with regular expressions. String extraction is also useful; being able to take just part of a string and manipulate it allows you to have more control over the final result. In Script 8.4 , we'll take a list of names entered in first-name-first order and swap them so that they're in last- name -first order.
| 1. | var re = /\s*\n\s*/; Here's a new regular expression, which simply searches for a pattern that consists of any white space \s* , followed by a new line character \n , followed again by any white space \s* . |
| 2. | var nameList = inNameList.split(re); The string method split() takes the regular expression and applies it to the data entered by the user ( Figure 8.5 ), stored in inNameList . Every new line separates a name, and split() cuts up the entered data at each new line. The result is a string array of the entered names, one name per array element, stored in the array nameList . Figure 8.5. Here's the before version of the list. |
| 3. | re = /(\S+)\s(\S+)/; Next we'll need another regular expression, which splits each name into first and last names. It looks for any nonwhite space characters (\S+) followed by a single white space character \s , followed by any nonwhite space characters (\S+) . The parentheses are required around each group of characters so that the information can be used later. |
| | |
| 4. | for (var k=0; k<nameList.length; k++) { For each name in the nameList array, loop through the following line of code. |
| 5. | newNames[k] = nameList[k].replace (re, ", "); Remember those parentheses in step 3? When the replace() method is executed, the regular expression re breaks apart nameList into first and last names. Those parentheses tell JavaScript to store the first name in the regular expression property $1 and the last name in the regular expression property $2 . The replace() method then uses the second parameter passed to it to return the last name $2 , followed by a comma, followed by the first name $1 . The names, now in last-name-first order, are stored in the new array newNames . |
| 6. | for (k=0; k<newNames.length; k++) { newNameField += newNames[k] + "\n"; } This loop sets up a new variable newNameField , which will contain the revised version of the user-entered text. For each name in the newNames array, append that name followed by a new line character to newNameField . |
| | |
| 7. | return newNameField; We pass the result back up to update the Web page. This happens in the switch/case section: thisTag.value = nameList(thisTag.value); . The result is shown in Figure 8.6 . Figure 8.6. Here's the reordered version of the page. |