Regular Expressions: BackreferencesYou can refer to the submatches resulting from searching a string (that is, the text returned when a section of a regular expression is enclosed in parentheses) as $1 , $2 , $3 , up to $9 in your code, where $1 holds the text of the first submatch, $2 holds the text of the second submatch, and so on. These values, $1 to $9 , are called backreferences . (They're actually properties of the RegExp object, as discussed at the end of this chapter.) Here's an example to show how you can use $1 , $2 , $3 , and so on. In this case, I'm matching three words separated by spaces (spaces are matched with the \s code) using the regular expression /(\w+)\s*(\w+)\s*(\w+)/ . Because I've surrounded the match to each of the three words in parentheses, I can refer to those words in code just as $1 , $2 , and $3 , which means that to reverse the order of those words, I could just assemble a replacement string using those matches in reverse order: (Listing 20-09.html on the web site)<HTML> <HEAD> <TITLE>The Reverser</TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-- function reversem() { var regexp =/(\w+)\s*(\w+)\s*(\w+)/ document.form1.text1.value = document.form1.text1.value.replace(regexp, " ") } //--> </SCRIPT> </HEAD> <BODY> <H1>The Reverser</H1> <FORM NAME="form1"> Type three words: <BR> <INPUT TYPE="TEXT" NAME="text1"> <BR> <INPUT TYPE="BUTTON" VALUE="Reverse Order" ONCLICK="reversem()"> </FORM> </BODY> </HTML> You can see the results of this code in Figure 20.7. Note that you don't have to use $1 , $2 , $3 , up to $9 to refer to submatches at all of courseyou can use the array returned by the exec or match methods (which can hold many more than nine submatches). However, $1 , $2 , and $3 match the original regular expression syntax in languages such as Perl, and that syntax is available in JavaScript as well. Figure 20.7. Reversing word order.
|