0.0.1-alpha.2 • Published 2 years ago

@andideve/route-matcher v0.0.1-alpha.2

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

route-matcher

For helps you create a simple router with vanilla JavaScript

Route Matcher

// inside routes.js

const routes = [
  {
    path: '/',
  },
  {
    path: '/restaurants',
  },
  {
    path: '/restaurants/bookmark',
  },
  {
    path: '/restaurants/bookmark/:id',
  },
  {
    path: '/restaurants/:id',
  },
  {
    path: '/:page/:slug',
  },
];

module.exports = routes;

Basic usage example:

const routes = require('../routes');
const matchRoute = require('./match-route');

const matchByPath = matchRoute(routes, '/restaurants');
console.log(matchByPath);
// output: { path: '/restaurants', route: { path: '/restaurants' }, params: {} }

const matchWithParam = matchRoute(routes, '/restaurants/3q2r9u-23c');
console.log(matchWithParam);
/**
 * output:
 * {
    path: '/restaurants/3q2r9u-23c',
    route: { path: '/restaurants/:id' },
    params: { id: '3q2r9u-23c' }
  }
 */

const multipleParams = matchRoute(routes, '/about/us');
console.log(multipleParams);
/**
 * output:
 * {
    path: '/about/us',
    route: { path: '/:page/:slug' },
    params: { page: 'about', slug: 'us' }
  }
 */