Last active
October 10, 2019 16:37
-
-
Save rostegg/63a19447ff6314c6da7f7d3ab53ac60f to your computer and use it in GitHub Desktop.
Get all JS functions which declarated as objects from string using single regex
This file contains hidden or 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
| /* | |
| Return array, which contains match arrays | |
| Groups: | |
| [0] - whole function | |
| [1] - function name | |
| [2] - function signature (function(){} or ()=>{}) | |
| [3] - function parameters (if declarated as function()) | |
| [4] - function parameters (if declarated as ()=>) | |
| [5] - function body (without brackets) | |
| Or use named groups (?<groupName>...) if ES2018 | |
| */ | |
| const definedJsFunctionsAsObjectRegex = /^(?:const|let|var)\s*([A-z0-9]+)?\s*=\s(function\s*\(([^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*\)|\(([^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*\)\s*\=\>)\s*\{((?:[^}{]+|\{[^}{]*\}|[^}]|\}(\"|\'|\`))*)*\}/gm | |
| const str = ` | |
| let f = function(a,b) { | |
| console.log(gdhfsgdfg); | |
| } | |
| const f2 = (a,b, d) => { blabla } | |
| let f3 = function(){ | |
| fdgdhgf | |
| } | |
| function test() { | |
| const inner = (t, b) => { im must be undetected} | |
| const inner2 = function (a,b) { | |
| im must be undetected too | |
| } | |
| } | |
| // here checking for }" | |
| function(fds) { obj = {} return "}" } | |
| function r () { obj = {}; a = []; } | |
| function a(){console.log('a')} function b(){console.log('b')} | |
| `; | |
| let matches = [...str.matchAll(definedJsFunctionsAsObjectRegex)]; | |
| console.log(matches) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment