Skip to content

Instantly share code, notes, and snippets.

@miyaokamarina
Last active April 9, 2018 21:48
Show Gist options
  • Save miyaokamarina/ce1c374cb505ca3786c38afaa52661d9 to your computer and use it in GitHub Desktop.
Save miyaokamarina/ce1c374cb505ca3786c38afaa52661d9 to your computer and use it in GitHub Desktop.
Multi-line regexps in JS made easy
const regexp = (xs, ...ys) => (xs2, ...ys2) =>
new RegExp(
String.raw(xs, ...ys).replace(
// Find additional escape sequences,
// spaces, line breaks, comments:
/\\[#\n ]|#.*$|[\n ]/gm,
// Remove spaces, line breaks, comments,
// unescape additional sequences:
x => (x[0] === '\\' ? x[1] : ''),
),
String.raw(xs2, ...ys2),
);
const date = regexp`^
(?<year> \d{4}) - # Year
(?<month> \d{2}) - # Month
(?<day> \d{2}) # Day
$``u`; // ← Flags.
const { year, month, day } = date.exec('2018-03-29').groups;
console.log(`${parseInt(month)}/${parseInt(day)}/${parseInt(year)}`); // 3/29/2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment