pagex
📄 A simple router for the browser in Javascript. It works with RegExp and Paths:
; // Call a function if the current page is exactly `/users`; // Execute only if the current page is exactly `/books`if // ...
Due to the API that it has, it's also highly compatible with React (though purely accidentally):
// Basic routing in React <div> </div>;
Parameters
;
path
: the path or regex to be matched against the current url. This is the only required parameter and it has to be the first one.callback = (...args) => args
(optional): the function that will be called if the path matches (or if it doesn't and it's negated). Any value returned here will be the final value returned bypagex()
. The default function will return an array if matched, with any matched parameter inside. So it's always truthy when it's matched so you can doif (pagex('/hello')) {...}
.negate = false
(optional): set to true to call the function if NOT in this path. Really useful for the difficulty to do so otherwise in RegExp.url = window.location.pathname
(optional): the url path to compare it against. Will default to the current browser pathname if it's not provided.
Note: the callback
, negate
and url
can be in any order since they are of different type. The path
always has to be the first argument though.
Pseudo Example
If you have a large javascript codebase, you can split it the following way:
// Logic for all your pages. For example, analytics; // Logic specific for your /users page and subpages; // Logic specific for your /books page and subpages;
Path
A simple front-end router based on express.js router, which is based on path-to-regexp:
;
You can get the url parameters easily:
;
Make them optional:
// Note: ES6 default parameter shown here;
Regex
Originally the main way of doing this was with pure regex (that's why it's called pagex, from Page + Regex). However, the main way now is with paths that get converted internally to regex. If you want to use regex you can do so:
// Starts by a string; // When NOT in this page, since negating in regex is complex: stackoverflow.com/a/1240337; // Strict page; // Parameters from capturing groups, with required id; // Parameters from capturing groups, with optional id;