Regex Path Matcher

Illustrate how to define a custom route matcher using regular expressions for complex URL patterns.
// Function to test if a given path matches a given regular expression pattern
function regexPathMatcher(pattern, path) {
    const regex = new RegExp(pattern);
    return regex.test(path);
Defines a function regexPathMatcher which takes a regex pattern and a path string as input and returns true if path matches the pattern, false otherwise.
// Example usage
const routePattern = '^\/users\/(\d+)$';
const pathToTest = '/users/123';
const isMatch = regexPathMatcher(routePattern, pathToTest);
console.log(isMatch); // Outputs: true
Demonstrates how to use the regexPathMatcher function by testing if the '/users/123' path matches the provided pattern that represents a route for user profiles with numeric ids.
const patterns = [

// Function that tests a path against multiple patterns
function matchMultiplePatterns(patterns, path) {
    for (const pattern of patterns) {
        if (regexPathMatcher(pattern, path)) {
            return true;
    return false;
Defines a function matchMultiplePatterns that tests a path against an array of regex patterns. It returns true if the path matches any of the patterns, false if it doesn't match any.
// Using the matchMultiplePatterns
const pathToTestMultiple = '/orders/456';
const multipleMatchResult = matchMultiplePatterns(patterns, pathToTestMultiple);
console.log(multipleMatchResult); // Outputs: true
Shows how to use the matchMultiplePatterns function to check if the path '/orders/456' matches any pattern in a list of multiple patterns.