Cover by Marijn Haverbeke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

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 third example ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required