Search code examples
javascriptnode.jsstringslug

Regex Match Between Slug And Url


Hi I want to check my routes if matched or not. Here is simple url path;

/blog/:slug1/:slug2

And here is my route;

/blog/foo/bar

How can I match them?


Solution

  • you can use the RegExp object in JavaScript to match the route and the URL path using a regular expression:

    Voici an example :

    const route = '/blog/foo/bar';
    const urlPath = '/blog/:slug1/:slug2';
    
    const pattern = /^\/blog\/([^/]+)\/([^/]+)$/;
    
    const match = urlPath.match(pattern);
    if (match) {
        console.log('Route and URL path match!');
    } else {
        console.log('Route and URL path do not match.');
    }