January 2011
Intermediate to advanced
224 pages
5h 43m
English
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.
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 ...
Read now
Unlock full access