Skip to content

Instantly share code, notes, and snippets.

@noosxe
Last active August 29, 2015 14:09
Show Gist options
  • Save noosxe/4876313312c36ba226f5 to your computer and use it in GitHub Desktop.
Save noosxe/4876313312c36ba226f5 to your computer and use it in GitHub Desktop.
(/id/slug)+ style URI components parser
/**
* Breaks given uri into 'id' and 'slug' components
* Just provide it uri like /id1/slug1/id2/slug2...
*
* @param {string} uri to break into components
* @return {object} returns an object consisting of 'id' and 'slug' arrays
*/
function getURIComponents(uri) {
var pattern = /\/(?:([a-z][a-z0-9_-]+)|(?:(\d+)\/([a-z][a-z0-9_-]+)))/ig;
var components = { separators: [], groups: [], count: 0 };
var match;
components.groups.push([]);
while ((match = pattern.exec(uri)) !== null) {
if (match[1]) {
components.separators.push(match[1]);
components.groups.push([]);
} else {
components.groups[components.groups.length - 1].push({
id: match[2],
slug: match[3]
});
++components.count;
}
}
return components;
}
module.exports = getURIComponents;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment