using System.Text.RegularExpressions;
private static string GetJsFile(string filename) {
return @"function test1() {
private static string GetFunction(string jstext, string functionname) {
var start = Regex.Match(jstext, @"function\s+" + functionname + @"\s*\([^)]*\)\s*{");
throw new Exception("Function not found: " + functionname);
StringBuilder sb = new StringBuilder(start.Value);
jstext = jstext.Substring(start.Index + start.Value.Length);
var delimiters = "`/'\"";
string currentDelimiter = null;
var isMultilineComment = false;
while(brackets > 0 && i < jstext.Length) {
var c = jstext[i].ToString();
var wasEscape = isEscape;
if(isComment || !isEscape)
} else if(i > 0 && !isComment && (c == "*" || c == "/") && jstext[i-1] == '/') {
isMultilineComment = c == "*";
} else if(c == "\n" && isComment && !isMultilineComment) {
} else if(isMultilineComment && c == "/" && jstext[i-1] == '*') {
isMultilineComment = false;
} else if(delimiters.Contains(c)) {
currentDelimiter = (currentDelimiter == c) ? null : currentDelimiter ?? c;
if(currentDelimiter == null && !isComment) {
if(wasEscape) isEscape = false;
public static void Main()
var fileContent = GetJsFile("somefile.js");
for(var i = 1; i < 5; i++) {
Console.WriteLine(GetFunction(fileContent, "test" + i));
Console.WriteLine("-----------------------------------");