The capturing groups reference has a nice example that shows how to match a date in the format YYYY-MM-DD
and extract the year, month, and day. This is useful because it’s a common operation that you might need to do without the overhead of a full date parsing library:
function parseDate(input) { const parts = /^(d{4})-(d{2})-(d{2})$/.exec(input); if (!parts) { return null; } return parts.slice(1).map((p) => parseInt(p, 10));
} parseDate("2019-01-01"); parseDate("2019-06-19");
One of the most common complaints about regular expressions is how hard they are to read. If you’re using capturing groups, you can use named capturing groups to make your patterns a bit easier to understand:
function parseLog(entry) { const { author, timestamp } = /^(?<timestamp>d+),(?<author>.+)$/.exec( entry ).groups; return `${author} committed on ${new Date( parseInt(timestamp) * 1000 ).toLocaleString()}`;
} parseLog("1560979912,Caroline");
This one is nice because it shows how to parse a log entry, extract the timestamp and author, and format the result into something more readable. Someone reading the code for the first time will have an easier time understanding what the regex is doing.
Unicode character class escape
The Unicode character class escape page has a great example that illustrates how to detect if a string contains a character from different scripts. This can be useful if you are trying to detect strings in different languages without having to manually or exhaustively specify certain characters (or ranges of characters) in your pattern:
const mixedCharacters = "a??"; mixedCharacters.match(/p{Script=Latin}/u); mixedCharacters.match(/p{Script=Grek}/u); mixedCharacters.match(/p{sc=Cyrillic}/u);
Character classes
The regular expressions character classes might be considered one of the most basic features, but there is an example on the reference page showing how they can be powerful in certain use cases. The example shows how to match hexadecimal digits, and I like this because it illustrates how ranges work in combination with the i
flag to match without case sensitivity:
function isHexadecimal(str) { return /^[0-9A-F]+$/i.test(str);
} isHexadecimal("2F3"); isHexadecimal("beef"); isHexadecimal("undefined");