06.07.2017 Views

Mastering JavaScript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Data Structures and Manipulation<br />

Regular expressions<br />

If you are not familiar with regular expressions, I request you to spend time<br />

learning them. Learning and using regular expressions effectively is one of the most<br />

rewarding skills that you will gain. During most of the code review sessions, the first<br />

thing that I comment on is how a piece of code can be converted to a single line of<br />

regular expression (or RegEx). If you study popular <strong>JavaScript</strong> libraries, you will be<br />

surprised to see how ubiquitous RegEx are. Most seasoned engineers rely on RegEx<br />

primarily because once you know how to use them, they are concise and easy to test.<br />

However, learning RegEx will take a significant amount of effort and time. A regular<br />

expression is a way to express a pattern to match strings of text. The expression itself<br />

consists of terms and operators that allow us to define these patterns. We'll see what<br />

these terms and operators consist of shortly.<br />

In <strong>JavaScript</strong>, there are two ways to create a regular expression: via a regular<br />

expression literal and constructing an instance of a RegExp object.<br />

For example, if we wanted to create a RegEx that matches the string test exactly, we<br />

could use the following RegEx literal:<br />

var pattern = /test/;<br />

RegEx literals are delimited using forward slashes. Alternatively, we could construct<br />

a RegExp instance, passing the RegEx as a string:<br />

var pattern = new RegExp("test");<br />

Both of these formats result in the same RegEx being created in the variable pattern.<br />

In addition to the expression itself, there are three flags that can be associated with a<br />

RegEx:<br />

• i: This makes the RegEx case-insensitive, so /test/i matches not only test,<br />

but also Test, TEST, tEsT, and so on.<br />

• g: This matches all the instances of the pattern as opposed to the default of<br />

local, which matches the first occurrence only. More on this later.<br />

• m: This allows matches across multiple lines that might be obtained from the<br />

value of a textarea element.<br />

These flags are appended to the end of the literal (for example, /test/ig) or passed<br />

in a string as the second parameter to the RegExp constructor (new RegExp("test",<br />

"ig")).<br />

[ 76 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!