I’m working on a Javascript Router like Backbone, Sammy, Spin. But my requirements are very simple. We should be able to give it a set of routes and their corresponding callbacks and we should be able to process the browsers URL upon request.
How I can replace :id for working with numbers only and :slug for common slugs?
I wrote this code:
core.route = function(route, options, callback) {
var url = options.hash;
var route_segments = route.split('/').length-1;
var hash_segments = url.split('/').length-1;
var route_matcher = new RegExp(route.replace(/:[^\/]+/g, '([\\w-]+)'));
if (url.match(route_matcher)) {
if (route_segments === hash_segments){
callback();
}
}
};
core.route('/work/:slug/:id/', options, function() {
alert("work/example/id");
});
core.route('/work/:id/', options, function() {
alert("work/id/");
});
You’ll have to define what a slug looks like first. But
\d+matches strings of numerals in regex, so you could try this: