Created
May 9, 2015 00:34
-
-
Save nick-skriabin/63b80c7cccb3d5c4308c to your computer and use it in GitHub Desktop.
Tiny url-pattern matcher
This file contains hidden or 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
### | |
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