15 JavaScript Regex Patterns Every Developer Needs
The Regex Riddle: Why We Struggle to Master JavaScript Regex
We've all been there - staring at a seemingly simple string, trying to extract a specific piece of information, and yet, our regex pattern just won't cooperate. It's frustrating, and it's a common pain point for many developers. But fear not, dear reader, for we're about to demystify the world of JavaScript regex and provide you with 15 essential patterns to boost your coding productivity.
Table of Contents
- Email and URL Patterns
- Date and UUID Patterns
- Mastering Named Groups
- Exploring Unicode Property Escapes (ES2024)
- Advanced Matching with
matchAll() - Putting it all Together: Real-World Examples
Email and URL Patterns
When it comes to validating user input, email and URL patterns are a must-know. Let's start with a simple email pattern:
const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
This pattern matches most common email formats, but keep in mind that fully validating an email address is a complex task. For URLs, we can use the following pattern:
const urlPattern = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;
This pattern matches most common URL formats, including HTTP and HTTPS.
Date and UUID Patterns
When working with dates and UUIDs, we need to ensure that our regex patterns are precise. For dates, we can use the following pattern:
const datePattern = /^\d{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/;
This pattern matches dates in the format YYYY-MM-DD. For UUIDs, we can use the following pattern:
const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
This pattern matches most common UUID formats.
Mastering Named Groups
Named groups are a powerful feature in regex, allowing us to capture and reference specific parts of a match. Let's take a look at an example:
const pattern = /(?<year>\d{4})-(?<month>0[1-9]|1[012])-(?<day>0[1-9]|[12][0-9]|3[01])/;
const match = pattern.exec('2022-07-25');
console.log(match.groups); // { year: '2022', month: '07', day: '25' }
In this example, we define named groups for the year, month, and day. We can then access these groups using the groups property of the match object.
Exploring Unicode Property Escapes (ES2024)
ES2024 introduces a new feature called Unicode property escapes, which allows us to match Unicode characters based on their properties. Let's take a look at an example:
const pattern = /\p{L}+/gu;
const match = pattern.exec('Hello, world!');
console.log(match); // ['H', 'e', 'l', 'l', 'o']
In this example, we use the \p{L} syntax to match any Unicode letter. The u flag at the end of the pattern enables Unicode matching.
Advanced Matching with matchAll()
The matchAll() method allows us to match all occurrences of a pattern in a string, rather than just the first match. Let's take a look at an example:
const pattern = /\d+/g;
const match = '123 abc 456 def 789'.matchAll(pattern);
console.log(match); // [ [ '123' ], [ '456' ], [ '789' ] ]
In this example, we use the matchAll() method to match all occurrences of one or more digits in the string.
Putting it all Together: Real-World Examples
Let's take a look at a real-world example that combines some of the patterns we've learned:
const userData = 'John Doe john.doe@example.com 2022-07-25';
const pattern = /^(?<name>[a-zA-Z\s]+) (?<email>[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}) (?<date>\d{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]))$/;
const match = pattern.exec(userData);
console.log(match.groups); // { name: 'John Doe', email: 'john.doe@example.com', date: '2022-07-25' }
In this example, we define a pattern that matches a user's name, email address, and date of birth. We can then access these values using the groups property of the match object.
Key Takeaways
- Mastering regex patterns takes time and practice, but it's essential for any developer.
- Use named groups to capture and reference specific parts of a match.
- Take advantage of Unicode property escapes (ES2024) to match Unicode characters based on their properties.
- Use the
matchAll()method to match all occurrences of a pattern in a string.
FAQ
Q: What is the difference between match() and matchAll()?
A: match() returns the first match of a pattern in a string, while matchAll() returns all matches.
Q: How do I enable Unicode matching in my regex patterns?
A: You can enable Unicode matching by adding the u flag at the end of your pattern.
Q: What is a named group in regex?
A: A named group is a way to capture and reference a specific part of a match using a name, rather than an index.