Skip to content

Instantly share code, notes, and snippets.

@krmax44
Last active April 3, 2020 13:02
Show Gist options
  • Save krmax44/43ab6b86f55714e9d484f525fc51d442 to your computer and use it in GitHub Desktop.
Save krmax44/43ab6b86f55714e9d484f525fc51d442 to your computer and use it in GitHub Desktop.
/*
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