Skip to content

Instantly share code, notes, and snippets.

@joduplessis
Created September 19, 2019 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joduplessis/b451887f7c9fd731280a3567dc7dae65 to your computer and use it in GitHub Desktop.
Save joduplessis/b451887f7c9fd731280a3567dc7dae65 to your computer and use it in GitHub Desktop.
Simplistic matching of Express style URL parameters NOT using Regex.
function matchPathToUrl(path, url) {
const sanitizedUrl = url[0] == '/' ? url.substring(1) : url
const sanitizedPath = path[0] == '/' ? path.substring(1) : path
const sanitizedUrlParts = sanitizedUrl.split('/')
const sanitizedPathParts = sanitizedPath.split('/')
const pathBoundaries = sanitizedPath.split('/').map(part => part[0] == ':' ? -1 : part)
let values = {}
const passes = pathBoundaries.reduce((pass, part, index) => {
if (sanitizedUrlParts.length != sanitizedPathParts.length) return false
// If the part doesn't equal -1
// then the 2 should be the same
// otherwise return false
if (part != -1) {
if (sanitizedPathParts[index] != sanitizedUrlParts[index]) return false
} else {
// If the part does equal -1
// then it's a vairable
// We need to check that it exists
if (sanitizedUrlParts[index] == undefined || sanitizedUrlParts[index] == null) return false
values[sanitizedPathParts[index]] = sanitizedUrlParts[index]
}
return pass ? true : false
}, true)
return { passes, values }
}
// Returns:
// { passes: true, values: { teamId: '5ce12ae5ffd420dc2f5a6878', roomId: '5ce12ae5ffd420dc2f5a6878' }}
matchPathToUrl(
'/app/team/:teamId/room/:roomId',
'/app/team/5ce12ae5ffd420dc2f5a6878/room/5ce12ae5ffd420dc2f5a6878'
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment