Main Page

Multiline mode

It is, in fact, easier to use the word character class (
\w
):
var sToMatch = “First second third fourth fifth sixth”
var reWords = /(\w+)/g;
var arrWords = sToMatch.match(reWords);
This is just the latest example of how the same functionality can be achieved by different means.
Multiline mode
In the last section, you learned about the beginning and end of the line boundaries. If a string has only
one line, this is very straightforward. But what if there are multiple lines contained in a string? You
could use the
split()
method to separate the string into an array of lines, but then you’d have to match
the regular expression against each line.
To illustrate the problem, consider the following example:
var sToMatch = “First second\nthird fourth\nfifth sixth”
var reLastWordOnLine = /(\w+)$/g;
var arrWords = sToMatch.match(reLastWordOnLine);
The regular expression in this code wants to match a word at the end of a line. The only match contained in
arrWords
is
“sixth”
, because it is at the end of the string. However, there are two line breaks in
sToMatch
,
so really both
“second”
and
“fourth”
should also be returned. This is where
multiline mode
comes in.
To specify multiline mode, you need only add an
m
to the options of the regular expression. Doing so
causes the
$
boundary to match the new line character (
\n
) as well as the actual end of the string. If you
add this option, the previous example returns
“second”
,
“fourth”
, and
“sixth”
:
var sToMatch = “First second\nthird fourth\nfifth sixth”
var reLastWordOnLine = /(\w+)$/gm;
var arrWords = sToMatch.match(reLastWordOnLine);
Multiline mode also changes the behavior of the
^
boundary so that it matches immediately after a new
line character. For example, to retrieve the strings
“First”
,
“third”
, and
“fifth”
from the string in
the example, you can do this:
var sToMatch = “First second\nthird fourth\nfifth sixth”
var reFirstWordOnLine = /^(\w+)/gm;
var arrWords = sToMatch.match(reFirstWordOnLine);
Without specifying multiline mode, the expression would return only
“First”
.
Understanding the RegExp Object
A regular expression in JavaScript is an object just like everything else. You already know that regular
expressions are represented by the
RegExp
object, and you also know that it has methods, which have
212
Chapter 7
10_579088 ch07.qxd 3/28/05 11:38 AM Page 212


JavaScript EditorFree JavaScript Editor     Ajax Editor


©