Reputation: 55
I am trying to extract function names from a javascript file using regex.
The 2 cases are
Case 1:
{ 'test1': function(){},
'test2': function(){}
}
Case 2:
{ test1: function(){}
test2: function(){}
}
Expected result for either case : [test1, test2]
Now when i use this regex expression with this javascript code
contents.match(/(.+)(?=: function\()/g);
The current result i get is
[ '\t\'test1\'',
'\t\'test2\'']
How i get the expected result : [test1, test2] , without including special characters like \t \'
Thanks in advance
Upvotes: 1
Views: 156
Reputation: 163427
You could make use of 2 capturing groups.
In group 1 match either '
or "
and use a backreference \1
to match the same as what is matched in group 1 to prevent function names to start and end with a different quote like 'test1"
In group 2 capture the function name.
(["']?)([^"'\s{}]+)\1\s*:\s*function\(\)
In parts
(
Capture group 1
["']?
Match an optional '
or "
)
Close group(
Capture group 2
[^'"\s{}]+
Match 1+ times any char other than the listed using a negated character class)\1
Close group 2\s*:\s*
Match :
between 0+ whitespace charsfunction\(\)
Match function()const regex = /(["']?)([^"'\s{}]+)\1\s*:\s*function\(\)/gm;
const str = `{ 'test1': function(){},
'test2': function(){}
}
{ test1: function(){}
test2: function(){}
}
`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
console.log(m[2]);
}
Upvotes: 0
Reputation: 5703
capture any string (not a blank space, nor a '
or "
) when it may be followed by '
or "
, any whitespace, and : function
let contents = `
{ test1:function(){}
'test2' : function(){}
"tes-t2": function(){}
"teè#//st2" : function(){}
}
`
console.log(contents.match(/([^'"\s]+)(?=['"]?\s*:\s*function\()/g))
Upvotes: 1