Created
February 18, 2017 22:18
-
-
Save renaudtertrais/856c1e6aa464b960581a9b5c42d2c79b to your computer and use it in GitHub Desktop.
Convert regex matches to an object
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
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('[email protected]'); // { _global: "[email protected]", domain: "bar", user: "foo" } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment