Using Javascript regex to extract comment from inside function

I am downloading a js file via httprequest and trying to parse a specific line (in this case a comment) from the resulting text, but I am having problems with the regex.

function SampleTest() {
    this.test1 = function() {
        /* :DOM <div id="sampleDIV">You loaded the sample div</div> */
    };
    this.test2 = function() {
        /* :DOM <div>Second Div Loaded</div> */          
    }
}

      

In another script, I have the following functions:

var getElementFromComment = function(obj) {

    function getHTML(method) {
        var httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', 'SampleTest.js', false);
        httpRequest.send();
        var response = httpRequest.responseText;

        var re = new RegExp(method); //Not sure how to implement the regex
        var result = response.match(re);
        console.log(result);
    }

    for(var method in obj) {
        getHTML(method);
    }
}

var sampleTest = new SampleTest();
getElementFromComment(sampleTest);

      

The end result is extracting HTML from this comment in the SampleTest based on the function name that is passed in. In my case, I will loop through all the functions and extract the html string for each one after the other. I guess the correct approach would be this:

  • Get Javascript file via httprequest - already done
  • Find a function in SampleTest that matches the passed name in getHTML and return the entire function as a string through a regular expression.
  • Use a different regex to extract the string from within the function string starting with / *: DOM and ending with * / This should be a multi-line comment, although I'm only using one line for simplicity.
  • And finally, replace all the garbage like * and: DOM that should leave me the html line.

I can't just search for a file for a comment off the bat, because the file will likely contain multiple functions, each with its own comment. To put the whole thing into context, I am doing this because I want to be able to load HTML for javascript unit tests on the fly. The function will ultimately unit test all the functions of the object, get the HTML, load it, run the function, remove the HTML, and move to the next function.

UPDATE Thanks to all the help from the accepted answer to the poster, I was able to get everything that works. However, I had to make a few adjustments, such as adding support for multi-line comments, and replacing all the garbage characters after the fact, so that I can get a clean HTML string. My updated code is below.

function getHTML(method, str) {
        var commentMatch;
        var re = new RegExp(method+'\\s*=\\s*function[^}]+\\*/'); //Not sure how to implement the regex
        var fnMatch = str.match(re);
        if(fnMatch) {
            var fnEx = new RegExp('\/\*\s*:[^\s]+\s*(.*?|\n)\*\/', 'g');
            commentMatch = fnMatch[0].match(fnEx);
            var result = commentMatch[0].replace(/(\s*:DOM\s*)|(\*\/)|(\/\*)|(\*)/gm, '');
            result = result.replace(/^\s*/gm, '');
            if(commentMatch) {
                return result;
            }
        }
    }

      

+3


source to share


1 answer


If you are trying to extract a comment line from a piece of javascript code in a javascript string variable, you can do it like this:

var str = "function SampleTest() { \
    this.test = function() { \
        /* :DOM <div id=\"sampleDIV\">You loaded the sample div</div> */ \
    }; \
}";

var matches = str.match(/\/\*\s*:DOM\s*(.*?)\*\//);
if (matches) {
    alert(matches[1]);
}​

      

Working demo here: http://jsfiddle.net/jfriend00/hWCwA/


If the ": DOM" part is not always the same, you can use a slightly different version, for example:



var str = "function SampleTest() { \
    this.test = function() { \
        /* :DOM <div id=\"sampleDIV\">You loaded the sample div</div> */ \
    }; \
}";

var matches = str.match(/\/\*\s*:[^\s]+\s*(.*?)\*\//);
if (matches) {
    alert(matches[1]);
}​

      

Working demo here: http://jsfiddle.net/jfriend00/qpF3k/


OK, based on your comments, here's another shot at him. The following comment will be found after the function name. It will stop looking at the first one }

, so it shouldn't move on to the next function if it has no comments.

function findComment(funcName, str) {
    var commentMatch;
    var re = new RegExp("this\\." + funcName + "\\s*=\\s*function[^}]+\\*/");
    var funcMatch = str.match(re);
    if (funcMatch) {
        commentMatch = funcMatch[0].match(/\/\*\s*:[^\s]+\s*(.*?)\*\//);
        if (commentMatch) {
            return(commentMatch[1]);
        }
    }
    return null;
}

      

+1


source







All Articles