Created
September 19, 2019 12:47
-
-
Save joduplessis/b451887f7c9fd731280a3567dc7dae65 to your computer and use it in GitHub Desktop.
Simplistic matching of Express style URL parameters NOT using Regex.
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
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