Skip to content

Instantly share code, notes, and snippets.

@balazs4
Forked from DavidJCobb/regex.js
Created January 26, 2022 21:10
Show Gist options
  • Select an option

  • Save balazs4/f80ab2c4e59d3c36e14c8c9370040bbe to your computer and use it in GitHub Desktop.

Select an option

Save balazs4/f80ab2c4e59d3c36e14c8c9370040bbe to your computer and use it in GitHub Desktop.
Helper for defining regexes
//
// 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