I am trying to match a function call using Regex but is not giving on big JS file where nested calls of the same function are inside. For example below is the code in JS file
abc('hello', function(){
abc('hello1', function(){
abc('hello2', function() {
// Does some!
});
});
});
And I want to match only first call to identify the first parameter. The end result I am looking for is hello
. So doing like below to match first call
.replace(/(?:\r\n|\r|\n)/g, '').match(/abc\s*[^\"\']*\"([^\"\']*)\"/);
Any suggestions please?
I am trying to match a function call using Regex but is not giving on big JS file where nested calls of the same function are inside. For example below is the code in JS file
abc('hello', function(){
abc('hello1', function(){
abc('hello2', function() {
// Does some!
});
});
});
And I want to match only first call to identify the first parameter. The end result I am looking for is hello
. So doing like below to match first call
.replace(/(?:\r\n|\r|\n)/g, '').match(/abc\s*[^\"\']*\"([^\"\']*)\"/);
Any suggestions please?
You can use a JS parser like Esprima to do this. This would be the correct and reliable solution rather than a magical regex, in my opinion. Regex's are often hard to maintain and often fail for edge cases. They are very useful in some cases, but this isn't one of them.
To try out Esprima, use this tool:
Esprima Demo
And input:
abc('hello', function(){
abc('hello1', function(){
abc('hello2', function() {
/* ... */
});
});
});
abc('hello3', function(){
abc('hello4', function(){
abc('hello5', function() {
/* ... */
});
});
});
Then filter the returned JSON to find only the first "level" functions and their first argument:
JSON.body.filter(function(token) {
return token.type === 'ExpressionStatement' && token.expression.type ===
'CallExpression' && token.expression.callee.name === "abc"
}).map(function(funcToken) {
return funcToken.expression.arguments[0].value
})
Which returns, in the example's case:
["hello", "hello3"]