• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 20. The RegExp Object: Working w... > Regular Expressions: Backreferences

Regular Expressions: Backreferences

You 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:


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint