Last active
October 10, 2019 16:37
-
-
Save rostegg/b23378138b98bec2f886ab381c08c16e to your computer and use it in GitHub Desktop.
Get all JS functions 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 parameters string | |
[3] - function body (excluding brackets) | |
Or use named groups (?<groupName>...) if ES2018 | |
*/ | |
const definedJsFunctionsRegex = /function\s*([A-z0-9]+)?\s*\(([^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*\)\s*\{((?:[^}{]+|\{[^}{]*\}|[^}]|\}(\"|\'|\`))*)*\}/g; | |
const testStr = ` | |
function a (a,b) { hfgdhfhjg | |
fdgdhfytr | |
confsf | |
dfdasg | |
} | |
function test() { | |
fdsf | |
consol.gkgd("fsdfs"); | |
const a = function(m) {fuck you}; | |
a(); | |
return 1 | |
} | |
function(fds) { obj = {} return "}" } | |
function r () { obj = {}; a = []; } | |
function test(float, best) { | |
console.log("Well"); | |
} | |
function a(){console.log('a')} function b(){console.log('b')} | |
`; | |
let matches = [...testStr.matchAll(definedJsFunctionsRegex)]; | |
console.log(matches); | |
/* | |
Example output: | |
(7) […] | |
| |
0: Array(5) [ "function a (a,b) { hfgdhfhjg\n fdgdhfytr\n confsf \n dfdasg \t\n }", "a", "a,b", … ] | |
| |
1: Array(5) [ "function test() {\n fdsf\n consol.gkgd(\"fsdfs\");\n const a = function(m) {fuck you};\n a();\n return 1\n }", "test", undefined, … ] | |
| |
2: Array(5) [ "function(fds) { obj = {} return \"}\" }", undefined, "fds", … ] | |
| |
3: Array(5) [ "function r () { obj = {}; a = []; }", "r", undefined, … ] | |
| |
4: Array(5) [ "function test(float, best) { \n console.log(\"Well\");\n }", "test", "float, best", … ] | |
| |
5: Array(5) [ "function a(){console.log('a')}", "a", undefined, … ] | |
| |
6: Array(5) [ "function b(){console.log('b')}", "b", undefined, … ] | |
| |
length: 7 | |
| |
<prototype>: Array [] | |
debugger eval code:31:9 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment