Skip to content

Instantly share code, notes, and snippets.

@nicholasrq
Created May 9, 2015 00:34
Show Gist options
  • Save nicholasrq/63b80c7cccb3d5c4308c to your computer and use it in GitHub Desktop.
Save nicholasrq/63b80c7cccb3d5c4308c to your computer and use it in GitHub Desktop.
Tiny url-pattern matcher
###
Example:
Pattern: http{s}://example.com
Will match:
http://example.com
https://example.com
Pattern: http{s}://example.com/*
Will match:
http://example.com/[anything]
https://example.com/[anything]
Pattern: http{s}://example.*/home
Will match:
http://example.[anything]/home
https://example.[anything]/home
Pattern: http{s}://example.com/[hello,world]
Will match:
http://example.com/hello[anything]
http://example.com/world[anything]
https://example.com/hello[anything]
https://example.com/world[anything]
###
url_match = (url, pattern='*')->
# trim enclosing slash(es) in url
url = url.replace(/([\/]*)$/g, '')
# trim enclosing slash(es) in pattern
pattern = pattern.replace(/([\/]*)$/g, '')
# allow wildcard pattern: *
pattern = pattern.replace(/\*/g, '(.+)')
# allow `any` pattern: [a,b,c]
pattern = pattern.replace(/\[([^\[\]]+)\]/g, (m)->
'(' + m.replace(/(\[|\])/g,'').split(',').join('|') + ')'
)
# allow `optional`: {smth}
pattern = pattern.replace(/\{([^\{\}]+)\}/g, (m)->
'(' + m.replace(/(\{|\})/g,'') + '*)'
)
matcher = new RegExp("^#{pattern}", 'g')
return matcher.test(url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment