Book Image

Javascript Regular Expressions

Book Image

Javascript Regular Expressions

Overview of this book

Table of Contents (13 chapters)

Creating a Regex for a telephone number


To tie up this chapter, let's put together a few of these features we just learned about and construct the phone number pattern we used in the previous chapter. To sum it up, we want to be able to match all the following number patterns:

123-123-1234
(123)-123-1234
1231231234

So, first off, we can see that there are optional brackets around the first three numbers (the area code), and we also have optional dashes between the numbers. This is a situation where the question mark character comes in handy. For the numbers themselves, we can use a built-in matcher to specify that they have to be numbers and a strong multiplier to specify exactly how many we need. The only special thing we need to know here is that the parenthesis contains special characters, so we will need to escape them (add a backslash):

/\(?\d{3}\)?-?\d{3}-?\d{4}/g

Note

Parentheses are used to define groups in regular expressions, this is why they are special characters. We will learn about...