Find all javascript funtion names in the file using Python

I have just learned that Closure Compiler in advanced mode does not work well with jQuery. Because of it I would like to compile my .js file in two steps: 1. Prepare .js file and replace all function names with something else. simple obfuscator. 2. use Closure Compiler in standard mode to replace variables

For the step 1. I thought Python could be a good tool. My code could be quite simple

# Read in the file
with open('file.js', 'r') as file :
  filedata =
filedata = filedata.replace('function-name', 'new-name')
...more ....

# Write the file out again
with open('file-output.js', 'w') as file:

Now the problem is that I do not want manually write the function names in my python program , but I want the program to find all function names and replace it with some names like f001, f002, f003...etc. All in the loop.

The input file is javaScript file, so basically the structure is always like this:

function NAME(

the point is to find all NAME's and add them to the list. Afterwards go via all names and replace them with string f001,f002...etc.

Could anybody advise me what will be regular expression to do this?

1st UPDATE: first part I did:

match = re.findall(r'function \w+', filedata)
if match:

Now I get a list of functions, but it gives me something like this 'function OnClickCanvas', so I need to remove 'function ' from that string.

1 answer

  • answered 2017-06-17 18:15 rdr

    maybe does not look nice, but works:

    match = re.findall(r'function \w+', filedata)
    if match:
        ret = re.sub('function ','', str(match))
        names = eval(ret)
    for item in names:

    gives me a list of functions. I get then in array 'names'.

    Maybe somebody has an idea how to make this code better?