0 0 0 0


I'm trying to pull code comment blocks out of JavaScript files. I'm making a light code documentator.

An example would be:

/** @Method: setSize
 * @Description: setSize DESCRIPTION
 * @param: setSize PARAMETER

I need to pull out the comments setup like this, ideally into an array.

I had gotten as far as this, but realize it may not handle new lines tabs, etc.:


(Okay, this seems like it would be simple, but I'm going in circles trying to get it to work.)

Best Answer:

Depending on what you want to continue doing with the extracted docblocks, multiple approaches come to mind. If you simply need the docblocks without further references, String.match() may suffice. Otherwise you might need the index of the block.

As others have already pointed out, javascript's RegEx machine is everything but powerful. if you're used to PCRE, this feels like working with your hands tied behind your back. [sS] (space-character, non-space-character) is equivalent to dotAll - also capturing linebreaks.

This should get you started:

var string = 'var foo = "bar";'
    + 'nn'
    + '/** @Method: setSize'
    + 'n * @Description: setSize DESCRIPTION'
    + 'n * @param: setSize PARAMETER'
    + 'n */'
    + 'n'
    + 'function setSize(setSize) { return true; }'
    + 'nn'
    + '/** @Method: foo'
    + 'n * @Description: foo DESCRIPTION'
    + 'n * @param: bar PARAMETER'
    + 'n */'
    + 'n'
    + 'function foo(bar) { return true; }';
var docblock = //*{2}([sS]+?)*//g,
    trim = function(string){ 
        return string.replace(/^s+|s+$/g, ''); 
    split = function(string) {
        return string.split(/[rn]s**s+/);
// extract all doc-blocks
// extract all doc-blocks with access to character-index
var match;
while (match = docblock.exec(string)) {
        match.index + " characters from the beginning, found: ", 

Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs