You are previewing Eloquent JavaScript.

Eloquent JavaScript

Cover of Eloquent JavaScript by Marijn Haverbeke Published by No Starch Press

Matching and Replacing

Often, looking for a pattern is just the first step in extracting something from a string. In previous chapters, such extraction was done by calling a string’s indexOf and slice methods. Now that we know about regular expressions, we can do better.

The match Method

Strings have a method named match, which takes a regular expression as an argument. It returns null if the match failed and returns an array of matched strings if it succeeded. You can see this happen in the following examples:

→ null

"... yes".match(/yes/i);
→ ["yes"]

"Giant Ape".match(/giant (\w+)/i);
→ ["Giant Ape", "Ape"]

The first element in the returned array is always the part of the string that matched the whole pattern. As the third example ...

The best content for your career. Discover unlimited learning on demand for around $1/day.