Real-World Validation PatternsLesson 5.2
URL validation and parsing with regex
URL components, protocol matching, optional www, path and query string, fragment, named groups for parsing, URL constructor alternative
Parse URLs Into Components With Named Groups
Regex can both validate and parse a URL into components in one pass using named groups.
const urlRe = /^(?<protocol>https?):\/\/(?<host>[\w.\-]+)(?<path>\/[^?#]*)?(?:\?(?<query>[^#]*))?(?:#(?<fragment>.*))?$/i;
const m = 'https://example.com/blog/post?id=1#comments'.match(urlRe);
// m.groups.protocol => 'https'
When to Use the URL Constructor Instead
try {
const u = new URL('https://example.com/path');
console.log(u.hostname); // 'example.com'
} catch {
console.log('Invalid URL');
}
