Basic Usage of URL Pattern API
The URL Pattern API provides a way to define and match URL patterns on the web platform. It supports wildcards, named groups, and regular expression groups, allowing you to match entire URLs or specific components.
https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API
Basic Usage
1. Creating a URLPattern
You can create a URLPattern
object to define a URL pattern. Patterns can be specified using an object for each URL component or as a string for the entire URL.
// Define pattern using an object
const pattern = new URLPattern({ pathname: '/books/:id' });
// Define pattern using a string
const patternString = new URLPattern('https://example.com/books/:id');
2. Matching Patterns
Use the test()
method to check if a specific URL matches the pattern.
console.log(pattern.test('https://example.com/books/123')); // true
console.log(patternString.test('https://example.com/books/456')); // true
3. Extracting Groups
The exec()
method allows you to extract matching parts, which is useful for named groups.
const result = pattern.exec('https://example.com/books/123');
console.log(result.pathname.groups.id); // '123'
4. Using Wildcards and Regular Expressions
Patterns can include wildcards (*
) or regular expressions.
const wildcardPattern = new URLPattern({ hostname: '*', pathname: '/foo/*' });
console.log(wildcardPattern.test('https://anydomain.com/foo/bar')); // true
const regexPattern = new URLPattern('/post/:id(\\d+)');
const namedGroup = regexPattern.exec('https://example.com/post/123').pathname.groups;
console.log(namedGroup.id); // '123'
Considerations
- Browser Support: This API is supported in some browsers like Chrome, Edge, and Opera.
- Experimental Feature: Ensure compatibility before using it in production environments.
The URL Pattern API helps standardize routing in web applications by providing a structured way to handle URLs.