Home > Mobile >  Regex Match Between Slug And Url
Regex Match Between Slug And Url

Time:12-09

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?

CodePudding user response:

A ‘slug' is the part that comes at the very end of a URL, and refers to a specific page or post. Usually a combination of word that separated with hyphen This expression can be used to validate an url slug with only lowercase alphabet or numbers on each word.

For example, in https://github.com/geongeorge/i-hate-regex , i-hate-regex is the slug

CodePudding user response:

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.');
}

  • Related