Last active
April 3, 2020 13:02
-
-
Save krmax44/43ab6b86f55714e9d484f525fc51d442 to your computer and use it in GitHub Desktop.
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
/* | |
I stumbled upon the Python-syntax for creating a RegEx, and decided to spend a minute trying to replicate | |
it in JavaScript with Template String Functions. I certainly have no use for it but there you go. | |
*/ | |
function combine(...args) { | |
const parts = args.shift(); | |
const inserts = [...args, '']; | |
return parts.reduce((a, b, i) => (a += b + inserts[i]), '') | |
} | |
function r(...args) { | |
return new RegExp(combine(...args)); | |
} | |
// Example: | |
const regex = r`[0-9]+`; | |
console.log(regex.test('69')); // true | |
// Bonus snippet: no bytes wasted [81b] | |
let r=(...a)=>new RegExp(a.shift().reduce((b,c,i)=>b+c+(a.length<=i?'':a[i]),'')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment