Created
March 15, 2015 22:55
-
-
Save msaglietto/de7a0132612c6c7e980f to your computer and use it in GitHub Desktop.
Simple route parser to extract parameters from a url given a format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var SimpleRouteParser = function(format) { | |
var namedParam = /\/(:(\w+))/g, | |
names, | |
route, | |
setFormat = function(format) { | |
if (!format) throw new Error('Please specify the url format'); | |
names = []; | |
route = format.replace(namedParam, function(match, param, name) { | |
//Store names to build the hash later | |
names.push(name); | |
return '/([^/?]+)'; | |
}); | |
route = new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$'); | |
}, | |
parseQueryString = function(storeIn, queryString) { | |
var queryRegex = /\&?([^=]+)\=([^&]+)/g; | |
while ((parsed = queryRegex.exec(queryString)) !== null) { | |
storeIn[parsed[1]] = parsed[2]; | |
} | |
}; | |
setFormat(format || '/'); | |
return { | |
parse: function(url) { | |
var parsed, i, hash = {}; | |
if (!route || !route.exec) throw new Error('Error getting the route Regex'); | |
parsed = route.exec(url); | |
if (parsed) { | |
//Match names to parameters | |
for (i = 1; i <= names.length; i += 1) { | |
hash[names[i - 1]] = parsed[i]; | |
} | |
if (parsed.length > names.length) { | |
//parseQueryString could return an object and extend hash with the result | |
//But to not add underscore or something like that and dont iterate here I just send the hash | |
parseQueryString(hash, parsed[i]); | |
} | |
} | |
return hash; | |
}, | |
format: setFormat | |
}; | |
}; | |
//Usage | |
var route = new SimpleRouteParser('/:version/api/:collecton/:id'); | |
console.log(route.parse('/6/api/listings/3?sort=desc&limit=10')); | |
console.log(route.parse('/6/api/listings/3')); | |
route.format('/'); | |
console.log(route.parse('/6/api/listings/3?sort=desc&limit=10')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment