Skip to content

Instantly share code, notes, and snippets.

@simenbrekken
Last active August 29, 2015 13:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simenbrekken/9369290 to your computer and use it in GitHub Desktop.
Save simenbrekken/9369290 to your computer and use it in GitHub Desktop.
Simple RegExp-based Router
// "Routes"
function Home() {
console.log('Home')
}
function Products(params) {
console.log(params.category, 'products')
}
function ProductDetails(params) {
console.log('Product #' + params.id)
}
function NotFound() {
console.log('Not found :(')
}
var router = new Router()
router.add('/', Home)
router.add(/^\/products\/([0-9]+)$/, ProductDetails, 'id')
router.add('/products/:category', Products)
router.add('*', NotFound)
console.log(router.match('/'))
console.log(router.match('/products/sports'))
console.log(router.match('/products/123'))
console.log(router.match('/nope'))
'use strict';
function Router(routes) {
this.routes = routes || []
}
Router.prototype.add = function(pattern, handler) {
var route = {
names: [],
handler: handler
}
if (pattern instanceof RegExp) {
route.pattern = pattern
route.names = Array.prototype.slice.call(arguments, 2)
} else if (typeof pattern == 'string') {
route.pattern = new RegExp('^' + pattern.replace(/\*/g, '(.*)').replace(/(?::([^\/]+))/g, function(match, name) {
route.names.push(name)
return '([^\/]+)'
}) + '$')
} else {
route = pattern
}
this.routes.push(route)
return route
}
Router.prototype.match = function(url) {
for (var i = 0, l = this.routes.length; i < l; i++) {
var route = this.routes[i]
var matches = route.pattern.exec(url)
if (matches) {
var names = route.names,
params = {}
for (var j = 0, k = names.length; j < k; j++) {
params[names[j]] = matches[j + 1]
}
return {
params: params,
handler: route.handler
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment