Book Image

Javascript Regular Expressions

Book Image

Javascript Regular Expressions

Overview of this book

Table of Contents (13 chapters)

Matching groups in Regex


The last main topic that I have left out until now is groups. However, in order to work with groups, we have to move back into a JavaScript console, as this will provide the actual results object that we will need to look at.

Groups show how we can extract data from the input provided. Without groups, you can check whether there is a match, or if a given input text follows a specific pattern. However, you can't take advantage of vague definitions to extract relevant content. The syntax is fairly simple: you wrap the pattern you want inside brackets, and then this part of the expression will be extracted in its own property.

Grouping characters together to create a clause

Let's start with something basic—a person's name—in standard JavaScript. If you had a string with someone's name, you would probably split it by the space character and check whether there are two or three components in it. In case there are two, the first would consist of the first name and the second...