Coding the Trim Function

The Trim function ensures that pattern matching occurs on the appropriate portion of the string the user entered by removing leading and trailing white spaces from the string. The following line of code shows how to use properties $1 through $9 of the RegExp object with the replace method of the RegExp object to return a trimmed string:

return oldString.replace(/^\s*(.*\S+)\s*$/,"$1");

The oldString variable is the original string, which is replaced by the content of $1 and used by the validateForm function. The code specifies $1 because the pattern contains one set of parentheses. The content of $1 is (.*\S+), meaning any non-white-space character and any number of white spaces between the words. If the pattern has two sets of parentheses, properties $1 and $2 are available; three sets enable properties $1, $2, and $3, and so forth. Referring to a $ property that has no associated set of parentheses does not cause an error; the $ property returns an empty string. The character string \s*, which occurs before and after the inner parentheses, indicates white spaces.

Note  When a pattern contains multiple parenthesized patterns, the patterns are assigned to properties $1 through $9 from left to right, regardless of whether the patterns are nested. However, nesting patterns does affect the results of the pattern matching; the $1 property contains the results of the pattern matching for all nested, parenthesized patterns.