Video of regular expressions with phone numbers:

This tutorial is going to look at a JavaScript regular expression example using zip codes and break down all the pieces.  The problem I’ve found with regular expressions is they aren’t something you can just look at and understand right away.  They use their own syntax that isn’t easy to decipher so that is what makes them hard to understand.

Let’s take a look at an example of one so they won’t be as intimidating.  Let’s say we want to use a regular expression to make sure that a zip code is typed correctly.  We will check for the regular zip code of 5 digits and also the format where it could be 5 digits followed by a dash or space and then followed by 4 more numbers.  The first thing we need to do is set up a variable that holds the string we are evaluating:

var zip = “78998”;

Next, we will set up the pattern that it compare against and save that into a variable as well:

var pattern = /^\d{5}(-?\s?\d{4})?\$/;

This looks crazy right?  Well, if we break it down piece by piece, it’s really not too bad.  So let’s do just that:

1.  The first part of the patter is a / and that means the pattern is beginning.  You need to define where the pattern starts and ends.  You do that with slashes like so:  / pattern /
2. The ^ means it has to start with whatever follows in the pattern.  When combined with a \$, which you see at the end of the pattern, that sets up the number of items that can be in the pattern.  For example, if I had the pattern of /^the\$/  that would only match the word “the” and nothing else.  It has to be three letters and those three letters have to be t, h, e spelling out “the”.
3. The next part \d{5} means 5 digits.  The \d means a number and the {5} means five of them in a row.  So ^\d{5} means the zip code must start with five numbers.
4. The next part (-?\s?\d{4})?  is the most complex of the group.  The parenthesis at the beginning and end groups all of these together and the ? mark at the end means the whole group is optional, they don’t have to appear in the zip code for a match.  Inside the parenthesis, we have a -? which means the dash individually is optional,  \s? means the space is optional as well, and \d{4} means the space or dash would be followed by four more digits.  And the ? at the end means the whole group as whole isn’t required either.
5. The last part is the \$ sign which works with the ^ to say this zip code has to be 5 digits total or 9 digits total with an optional dash and/or space.  No more, no less.

Once the pattern is set up, all we need to do is apply that pattern to the zip code variable and see if it passes the test or not.  We can use the “test” method to do that like so:

If it passes the comparison, then this would alert “true” and if it doesn’t pass the test it would alert “false”.  The final code would look something like this:

<!DOCTYPE html>
<html>