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:

"No".match(/yes/i);
→ 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 ...

Get Eloquent JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.