18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 7<br />

It is, in fact, easier to use the word character class (\w):<br />

var sToMatch = “First second third fourth fifth sixth”<br />

var reWords = /(\w+)/g;<br />

var arrWords = sToMatch.match(reWords);<br />

This is just the latest example of how the same functionality can be achieved by different means.<br />

Multiline mode<br />

In the last section, you learned about the beginning and end of the line boundaries. If a string has only<br />

one line, this is very straightforward. But what if there are multiple lines contained in a string? You<br />

could use the split() method to separate the string into an array of lines, but then you’d have to match<br />

the regular expression against each line.<br />

To illustrate the problem, consider the following example:<br />

var sToMatch = “First second\nthird fourth\nfifth sixth”<br />

var reLastWordOnLine = /(\w+)$/g;<br />

var arrWords = sToMatch.match(reLastWordOnLine);<br />

The regular expression in this code wants to match a word at the end of a line. The only match contained in<br />

arrWords is “sixth”, because it is at the end of the string. However, there are two line breaks in sToMatch,<br />

so really both “second” and “fourth” should also be returned. This is where multiline mode comes in.<br />

To specify multiline mode, you need only add an m to the options of the regular expression. Doing so<br />

causes the $ boundary to match the new line character (\n) as well as the actual end of the string. If you<br />

add this option, the previous example returns “second”, “fourth”, and “sixth”:<br />

var sToMatch = “First second\nthird fourth\nfifth sixth”<br />

var reLastWordOnLine = /(\w+)$/gm;<br />

var arrWords = sToMatch.match(reLastWordOnLine);<br />

Multiline mode also changes the behavior of the ^ boundary so that it matches immediately after a new<br />

line character. <strong>For</strong> example, to retrieve the strings “First”, “third”, and “fifth” from the string in<br />

the example, you can do this:<br />

var sToMatch = “First second\nthird fourth\nfifth sixth”<br />

var reFirstWordOnLine = /^(\w+)/gm;<br />

var arrWords = sToMatch.match(reFirstWordOnLine);<br />

Without specifying multiline mode, the expression would return only “First”.<br />

Understanding the RegExp Object<br />

A regular expression in <strong>JavaScript</strong> is an object just like everything else. You already know that regular<br />

expressions are represented by the RegExp object, and you also know that it has methods, which have<br />

212

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!