Created
June 5, 2020 12:32
-
-
Save ncruces/04ef282b63ecfb28e1bc1e93a03d1a7a to your computer and use it in GitHub Desktop.
Multi-line RegExp with comments
This file contains 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
function regexp(...args) { | |
function cleanup(string) { | |
// remove whitespace, single and multi-line comments | |
return string.replace(/\s+|\/\/.*|\/\*[\s\S]*?\*\//g, ''); | |
} | |
function escape(string) { | |
// escape regular expression | |
return string.replace(/[-.*+?^${}()|[\]\\]/g, '\\$&'); | |
} | |
function create(flags, strings, ...values) { | |
let pattern = ''; | |
for (let i = 0; i < values.length; ++i) { | |
pattern += cleanup(strings.raw[i]); // strings are cleaned up | |
pattern += escape(values[i]); // values are escaped | |
} | |
pattern += cleanup(strings.raw[values.length]); | |
return RegExp(pattern, flags); | |
} | |
if (Array.isArray(args[0])) { | |
// used as a template tag (no flags) | |
return create('', ...args); | |
} | |
// used as a function (with flags) | |
return create.bind(void 0, args[0]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment