-
-
Save balazs4/f80ab2c4e59d3c36e14c8c9370040bbe to your computer and use it in GitHub Desktop.
Helper for defining regexes
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
| // | |
| // This file contains a JavaScript tag function to let you | |
| // define regexes without needing to backslash-escape every | |
| // forward slash in the regex text; good for URLs. | |
| // | |
| function regex(tag) { | |
| return new RegExp(tag.raw, "i"); | |
| } | |
| // | |
| // Examples: | |
| // | |
| // // using a normal regex literal | |
| // location.href.match(/https?\:\/\/(?:www\.)?nexusmods\.com\/(?:[^\/]+\/)?users\/(\d+)\/?(?:[#\?].*)?$/i); | |
| // | |
| // // using the function above on a template literal | |
| // location.href.match(regex `https?://(?:www\.)?nexusmods\.com/(?:[^/]+/)?users/(\d+)/?(?:[#\?].*)?$`); | |
| // | |
| // | |
| // Consider the following: | |
| // | |
| // // basic regex. lots of escaping for those forward slashes, since that's the | |
| // // delimiter for regex literals... can we avoid doing that? | |
| // location.href.match(/https?\:\/\/(?:www\.)?nexusmods\.com\/(?:[^\/]+\/)?users\/(\d+)\/?(?:[#\?].*)?$/i); | |
| // | |
| // // doesn't work: backslashes in template literals still act as escape sequences, | |
| // // so `\.` is "\." is /./ | |
| // location.href.match(new RegExp(`https?://(?:www\.)?nexusmods\.com/(?:[^/]+/)?users/(\d+)/?(?:[#\?].*)?$`, "i")); | |
| // | |
| // // works, but doubling each backslash is awkward. bit easy to forget, too | |
| // location.href.match(new RegExp("https?://(?:www\\.)?nexusmods\\.com/(?:[^/]+/)?users/(\\d+)/?(?:[#\\?].*)?$", "i")); | |
| // | |
| // // works, but is the longest syntax yet | |
| // location.href.match(new RegExp(String.raw `https?://(?:www\.)?nexusmods\.com/(?:[^/]+/)?users/(\d+)/?(?:[#\?].*)?$`, "i")); | |
| // | |
| // // the custom "regex" tag function mimics the behavior of String.raw, and | |
| // // passses the result to the RegExp constructor | |
| // location.href.match(regex `https?://(?:www\.)?nexusmods\.com/(?:[^/]+/)?users/(\d+)/?(?:[#\?].*)?$`); | |
| // |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment