JavaScript Regular Expressions - Sample Chapter
JavaScript Regular Expressions - Sample Chapter
ee
C o m m u n i t y
E x p e r i e n c e
D i s t i l l e d
Gabriel Manricks
P U B L I S H I N G
$ 34.99 US
22.99 UK
pl
Loiane Groner
JavaScript Regular
Expressions
Sa
m
JavaScript Regular
Expressions
Leverage the power of regular expressions to create an
engaging user experience
Loiane Groner
Gabriel Manricks
If you want to keep in touch with her, you can find her on Facebook (
) and on Twitter
).
Gabriel Manricks is a full-stack software and web developer, and a writer. He is the
CTO at CoinSimple and a staff writer at Nettuts+, where he enjoys learning as well
as teaching others. He also freelances in the fields of web consulting, development,
and writing.
[1]
We can describe this pattern as being three digits, a dash, then another three
numbers, followed by a second dash, and finally four more numbers. It is pretty
simple to do; we look at a string and describe how it is made up, and the preceding
description will work perfectly if all your numbers follow the given pattern. Now,
let's say, we add the following three phone numbers to this set:
123-123-1234
(123)-123-1234
1231231234
These are all valid phone numbers, and in your application, you probably want to be
able to match all of them, giving the user the flexibility to write in whichever manner
they feel most comfortable. So, let's have another go at our pattern. Now, I would say
we have three numbers, optionally inside brackets, then an optional dash, another
three numbers, followed by another optional dash, and finally four more digits. In
this example, the only parts that are mandatory are the ten digits: the placing of
dashes and brackets would completely be up to the user.
Notice also that we haven't put any constraints on the actual digits, and as a matter
of fact, we don't even know what they will be, but we do know that they have to be
numbers (as opposed to letters, for instance), so we've only placed this constraint:
[2]
Chapter 1
This is an example of some sort of log, of course, and we can simply say that each
line is a single log message. However, this doesn't help us if we want to manipulate
or extract the data more specifically. Another option would be to say that we have
some kind of word in brackets, which refers to the log level, and then a message after
the dash, which will consist of any number of words. Again, this isn't too specific,
and our application may only know how to handle the three preceding log levels, so,
you may want to ignore everything else or raise an error.
To best describe the preceding pattern, we would say that you have a word, which
can either be info, a warning, or an error inside a pair of square brackets, followed
by a dash and then some sort of sentence, which makes up the log message. This will
allow us to capture the information from the log more accurately and make sure our
system is ready to handle the data before we send it:
[3]
We could just say that the pattern consists of a tag, some text, and a closing tag. This
isn't really specific enough for it to be a valid XML, since the closing tag has to match
the opening one. So, if we define the pattern again, we would say that it contains
some text wrapped by an opening tag on the left-hand side and a matching closing
tag on the right-hand side:
The last three examples were just used to get us into the Regex train of thought; these
are just a few of the common types of patterns and constraints, which you can use in
your own applications.
Now that we know what kind of patterns we can create, let's take a moment to
discuss what we can do with them; this includes the actual features and functions
JavaScript provides to allow us to use these patterns once they're made.
Regex in JavaScript
In JavaScript, regular expressions are implemented as their own type of object (such
as the RegExp object). These objects store patterns and options and can then be used
to test and manipulate strings.
To start playing with regular expressions, the easiest thing to do is to enable a
JavaScript console and play around with the values. The easiest way to get a console
is to open up a browser, such as Chrome, and then open the JavaScript console on
any page (press the command + option + J on a Mac or Ctrl + Shift + J).
Let's start by creating a simple regular expression; we haven't yet gotten into the
specifics of the different special characters involved, so for now, we will just create
a regular expression that matches a word. For example, we will create a regular
expression that matches hello.
[4]
Chapter 1
Both these variables are essentially the same, it's pretty much a personal preference as
to which you would use. The only real difference is that with the constructor method
you use a string to create an expression: therefore, you have to make sure to escape any
special characters beforehand, so it gets through to the regular expression.
Besides a pattern, both forms of Regex constructors accept a second parameter,
which is a string of flags. Flags are like settings or properties, which are applied
on the entire expression and can therefore change the behavior of both the pattern
and its methods.
[5]
So, continuing from the preceding example, if we wanted to create the same pattern,
but this time, with the case set as insensitive and using global flags, we would write
something similar to this:
var rgx1 = new RegExp("hello", "gi");
var rgx2 = /hello/gi;
As you can see, the first string matches and returns true, and the second string does
not contain hello, so it returns false, and finally the last string matches the pattern.
In the pattern, we did not specify that the string had to only contain hello, so it
matches the last string and returns true.
[6]
Chapter 1
As you can see here, the result from the function contains the actual match as the first
element (rgx.exec("world !!")[0];) and if you console.dir the results, you will
see it also contains two properties: index and input, which store the starting index
property and complete the input text, respectively. If there are no matches, the
function will return null:
[7]
In order to replace all the occurrences, we need to supply a RegExp object that has
the g flag, as shown here:
[8]
Chapter 1
We have taken a quick pass through the most common uses of regular expressions in
JavaScript (code-wise), so we are now ready to build our RegExp testing page, which
will help us explore the actual syntax of Regex without combining it with JavaScript
code.
It is a fairly standard document head, and contains a title and some styles. Besides
this, I am including the bootstrap CSS framework for design, and the jQuery library
to help with the DOM manipulation.
[9]
Next, let's create the form and result area in the body:
<body>
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="alert alert-danger hide" id="alert-box"></div>
<div class="form-group">
<label for="input-text">Text</label>
<input
type="text"
class="form-control"
id="input-text"
placeholder="Text"
>
</div>
<label for="inputRegex">Regex</label>
<div class="input-group">
<input
type="text"
class="form-control"
id="input-regex"
placeholder="Regex"
>
<span class="input-group-btn">
<button
class="btn btn-default"
id="test-button"
type="button">
Test!
</button>
</span>
</div>
</div>
</div>
<div class="row">
<h3>Results</h3>
<div class="col-sm-12">
<div class="well well-lg" id="results-box"></div>
</div>
</div>
</div>
<script>
[ 10 ]
Chapter 1
//JS code goes here
</script>
</body>
</html>
Most of this code is boilerplate HTML required by the Bootstrap library for styling;
however, the gist of it is that we have two inputs: one for some text and the other
for the pattern to match against it. We have a button to submit the form (the Test!
button) and an extra div to display the results.
Opening this page in your browser should show you something similar to this:
textbox = $("#input-text");
regexbox = $("#input-regex");
alertbox = $("#alert-box");
resultsbox = $("#results-box");
$("#test-button").click(function(){
//clear page from previous run
clearResultsAndErrors()
//get current values
var text = textbox.val();
var regex = regexbox.val();
[ 11 ]
The first four lines select the corresponding DOM element from the page using
jQuery, and store them for use throughout the application. This is a best practice
when the DOM is static, instead of selecting the element each time you use it.
The rest of the code is the click handler for the submit (Test!) button. In the function
that handles the Test! button, we start by clearing the results and errors from the
previous run. Next, we pull in the values from the two text boxes and handle the
cases where they are empty using a function called err, which we will take a look
at in a moment. If the two values are fine, we attempt to create a new RegExp object
and we get their results using two other functions I wrote called createRegex and
getMatches, respectively. Finally, the last conditional block checks whether there
were results and displays either a No Matches Found message or an element on
the page that will show individual matches using getMatchesCountString to
display how many matches were found and getResultsString to display the
actual matches in string.
[ 12 ]
Chapter 1
The first function clears the text from the results element and then hides the previous
errors, and the second function un-hides the alert element and adds the error passed
in as a parameter.
[ 13 ]
If you try and create a RegExp object with flags that don't exist or invalid parameters,
it will throw an exception. Therefore, we need to wrap the RegExp creation in a try/
catch block, so that we can catch the error and display an error for it.
Inside the try section, we will handle two different kinds of RegExp input, the first
is when you use forward slashes in your expressions. In this situation, we split this
expression by forward slashes, remove the first element, which will be an empty
string (the text before it is the first forward slash), and then pop off the last element
which is supposed to be in the form of flags.
We then recombine the remaining parts back into a string and pass it in along
with the flags into the RegExp constructor. The other case we are dealing with is
where you wrote a string, and then we are simply going to pass this pattern to the
constructor with only the g flag, so as to get multiple results.
We have already seen the exec command earlier and how it returns a results
object for each match, but the exec method actually works differently, depending
on whether the global flag (g) is set or not. If it is not set, it will constantly just return
the first match, no matter how many times you call it, but if it is set, the function will
cycle through the results until the last match returns null. In the function, the global
flag is set, I use a while loop to cycle through results and push each one into the
results array, whereas if it is not set, I simply call function once and push only if
the first match on.
[ 14 ]
Chapter 1
Next, we have a function that will create a string that displays how many matches
we have (either one or more):
function getMatchesCountString(results) {
if (results.length === 1) {
return "<p>There was one match.</p>";
} else {
return "<p>There are " + results.length + " matches.</p>";
}
}
Finally, we have function, which will cycle through the results array and create
an HTML string to display on the page:
function getResultsString(results, text) {
for (var i = results.length - 1; i >= 0; i--) {
var result = results[i];
var match = result.toString();
var prefix = text.substr(0, result.index);
var suffix = text.substr(result.index + match.length);
text = prefix
+ '<span class="label label-info">'
+ match
+ '</span>'
+ suffix;
}
return "<h4>" + text + "</h4>";
}
Inside function, we cycle through a list of matches and for each one, we cut the
string and wrap the actual match inside a label for styling purposes. We need to
cycle through the list in reverse order as we are changing the actual text by adding
labels and also so as to change the indexes. In order to keep in sync with the indexes
from the results array, we modify text from the end, keeping text that occurs
before it, the same.
[ 15 ]
Whereas, if we specify the same pattern, though without the global flag, we would
only get the first match:
[ 16 ]
Chapter 1
Of course, if you leave out a field or specify an invalid pattern, our error handling
will kick in and provide an appropriate message:
With this all working as expected, we are now ready to start learning Regex by itself,
without having to worry about the JavaScript code alongside it.
Summary
In this chapter, we took a look at what a pattern actually is, and at the kind of data
we are able to represent. Regular expressions are simply strings that express these
patterns, and combined with functions provided by JavaScript, we are able to match
and manipulate user data.
We also covered building a quick RegExp builder that allowed us to get a first-hand
look at how to use regular expressions in a real-world setting. In the next chapter, we
will continue to use this testing tool to start exploring the RegExp syntax.
[ 17 ]
www.PacktPub.com
Stay Connected: