Skip to content

Instantly share code, notes, and snippets.

@renaudtertrais
Created February 18, 2017 22:18
Show Gist options
  • Save renaudtertrais/856c1e6aa464b960581a9b5c42d2c79b to your computer and use it in GitHub Desktop.
Save renaudtertrais/856c1e6aa464b960581a9b5c42d2c79b to your computer and use it in GitHub Desktop.
Convert regex matches to an object
const parseRgx = rgx => s => {
const keys = ['_global', ...rgx.match(/\$(\w+):/g).map(k => k.replace(/\$|:/g,''))];
const matches = s.match(new RegExp(rgx.replace(/\$\w+:/g,''))) || [];
return matches.reduce((res, val, i) => Object.assign({}, res, { [keys[i]]: val }), {});
};
const parseEmail = parseRgx('($user:\\w+)@($domain:\\w+)\\.(?:\\w+)');
parseEmail('foo@bar.com'); // { _global: "foo@bar.com", domain: "bar", user: "foo" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment