Last active
August 29, 2015 14:09
-
-
Save noosxe/4876313312c36ba226f5 to your computer and use it in GitHub Desktop.
(/id/slug)+ style URI components parser
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
/** | |
* 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