December 2023
Intermediate to advanced
242 pages
5h 28m
English
| Recipe 31 | Extracting a Matched Value with the Capturing Group |
Suppose you need to search for a file with a .pdf extension and extract only the filename without the extension. Typically, regular expressions return the entire matched string, but you want a solution that enables you to identify and extract a specific part of the matched string for further processing.
Place a pair of parentheses around the specific part of the pattern that you want to extract:
| | const re = /\b(\w+)\.pdf\b/; |
| | const str = "Please download data_p2x53.pdf"; |
| | |
| | const result = str.match(re); |
| | |
| | if (result) { |
| | console.log(result[1]) |
| | } else { |
| | console.error("No match found."); |
Read now
Unlock full access