Skip to content

Instantly share code, notes, and snippets.

@wilmoore
Last active August 2, 2024 23:54
Show Gist options
  • Select an option

  • Save wilmoore/947c6876896f1471fc2910431bfa7ee6 to your computer and use it in GitHub Desktop.

Select an option

Save wilmoore/947c6876896f1471fc2910431bfa7ee6 to your computer and use it in GitHub Desktop.
Software Engineering :: Programming :: Languages :: JavaScript :: String :: Instance :: String.prototype.replace() :: Example :: URI Template To RegExp

Software Engineering :: Programming :: Languages :: JavaScript :: String :: Instance :: String.prototype.replace() :: Example :: URI Template To RegExp

⪼ Made with 💜 by Polyglot.

related
research

URI Template To RegExp

RegExp for matching URI Template String
> '/users/{id}/comments/{commentId}'.replace(/{(?<parameter>[0-9a-zA-Z]+)}/g, '{(?<$<parameter>>[0-9a-zA-Z]+)}')
'/users/{(?<id>[0-9a-zA-Z]+)}/comments/{(?<commentId>[0-9a-zA-Z]+)}'

> RegExp('/users/{id}/comments/{commentId}'.replace(/{(?<parameter>[0-9a-zA-Z]+)}/g, '{(?<$<parameter>>[0-9a-zA-Z]+)}'))
/\/users\/{(?<id>[0-9a-zA-Z]+)}\/comments\/{(?<commentId>[0-9a-zA-Z]+)}/
RegExp for matching Request URL
> '/users/{id}/comments/{commentId}'.replace(/{(?<parameter>[0-9a-zA-Z]+)}/g, '(?<$<parameter>>[0-9a-zA-Z]+)')
'/users/(?<id>[0-9a-zA-Z]+)/comments/(?<commentId>[0-9a-zA-Z]+)'

> RegExp('/users/{id}/comments/{commentId}'.replace(/{(?<parameter>[0-9a-zA-Z]+)}/g, '(?<$<parameter>>[0-9a-zA-Z]+)'))
/\/users\/(?<id>[0-9a-zA-Z]+)\/comments\/(?<commentId>[0-9a-zA-Z]+)/
as a function
let templateToRegExp = null

templateToRegExp = (templateString) => {
  return RegExp(`^${templateString.replace(/{(?<parameter>[0-9a-zA-Z]+)}/g, '(?<$<parameter>>[0-9a-zA-Z]+)')}$`)
}

routeMatcher = (templateString) => {
  const pattern = RegExp(`^${templateString.replace(/{(?<parameter>[0-9a-zA-Z]+)}/g, '(?<$<parameter>>[0-9a-zA-Z]+)')}$`)
  return (endpoint) => pattern.test(endpoint)
}

> routeMatcher('/users/{id}')('/users/123')
true

let routes = {}

routes = {
  '/': { name: "root" },
  '/posts': { name: "posts" },
  '/posts/{id}': { name: "posts by id" },
  '/posts/{id}/comments': { name: "post by id comments" },
  '/posts/{id}/comments/{commentId}': { name: "post comments by id" },
}

Object.keys(routes).filter((uriTemplate) => routeMatcher(uriTemplate)('/posts/123'))

> Object.keys(routes).filter((uriTemplate) => routeMatcher(uriTemplate)('/users/123'))
[]
> Object.keys(routes).filter((uriTemplate) => routeMatcher(uriTemplate)('/posts/123'))
[ '/posts/{id}' ]

> Object.keys(routes).filter((uriTemplate) => routeMatcher(uriTemplate)('/posts/123/comments'))
[ '/posts/{id}/comments' ]
>
> Object.keys(routes).filter((uriTemplate) => routeMatcher(uriTemplate)('/posts/123/comments/432'))
[ '/posts/{id}/comments/{commentId}' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment