views:

68

answers:

2

I am writing a Plug-In for VS2008 and I would like to recognize the JavaScript method(function). I have a file - sample.js:`

     function test0()
     {
         var i = 0;
         {
             var j = 0;
         }
         var array = { 1: 2, dd: 10, aaa: 3 };
                    return array;
     }

     function test1()
     {
         var ii = "x";
         {
             var xx = "x" + ii;
         }
         return ii;
     }

`

How to recognize these methods? Use regular expressions?

A: 

Since function is a reserved keyword, it's safe to assume that as long as the word function is not in quotes it should be a javascript function.

Regex should work. Remember to check if the word is incased in quotes (which would make it a word a string).

asperous.us
+4  A: 

Remember that JavaScript functions can be written a few ways. You showed the "C" style function definition, but there are others.

You'll see a lot of "var test2=function(){}".

You'll also see them as members of objects "test3: function(){}".

And you can use "new," but that's not very popular.

And don't forget that many JavaScript functions are anonymous.

For good measure you should handle the immediate invocation pattern:

(function () {

  // ...

}());

Will the code that you'll see be restricted by some self-imposed rules? If not, you have some parsing to do when you see "function." Especially since "function" could just be a word in some text, and you have a couple different kinds of quotes and a couple kinds of comment styles to unravel to see if it's simply part of a text string or part of a comment.

Nosredna
Thanks for help. But how to identify internal brackets: "{", "}"Sample:function test1() { var ii = "x"; {// this is a problem for me var xx = "x" + ii; }// this is a problem for me return ii; }
mykhaylo
Could you edit your original question with a little more detail on your specific question? It's hard to read code in comments.
Nosredna
The regular expression that solves my problem: "function\\s*?\\([\\w,\\s]*?\\)\\s*?{([^{]|({.*?})*|[^}])*?}". A few more changes and everything should work. Thanks for hints.
mykhaylo
Cool. Good luck.
Nosredna