Get javascript comments in javascript or how to parse js in js?

I am looking for a way to access javascript comments from some (other) javascript code. I plan to use this to display low-level help information for elements on the page that call various js functions without duplicating this information in several places.

mypage.html:

...
<script src="foo.js"></script>
...
<span onclick="foo(bar);">clickme</span>
<span onclick="showhelpfor('foo');>?</span>
...

foo.js:

/**
 * This function does foo.
 * Call it with bar.  Yadda yadda "groo".
 */
function foo(x)
{
    ...
}

I believe that I can use getElementsByTagName to grab the script tag and then load the file with the AJAX request to get its text content. However, then I will need a method for parsing javascript (i.e. not a bunch of hacked regular expressions together) that stores characters that just make sure it throws away.

js, , , doxygen .

function foo(x) { ... }
foo.comment = "\
This functions does foo.\
Call it with bar.  Yadda yadda \"groo\".\
";
+3
2

, JS-, , - , .

JS, PEG.js, . :

{
var functions = {};
var buffer = '';
}

start
  =  unit* {return functions;}

unit
  =  func
  /  string
  /  multi_line_comment
  /  single_line_comment
  /  any_char

func
  =  m:multi_line_comment spaces? "function" spaces id:identifier {functions[id] = m;}
  /  "function" spaces id:identifier                              {functions[id] = null;}

multi_line_comment
  =  "/*" 
     ( !{return buffer.match(/\*\//)} c:. {buffer += c;} )*               
     {
       var temp = buffer; 
       buffer = ''; 
       return "/*" + temp.replace(/\s+/g, ' ');
     }

single_line_comment
  =  "//" [^\r\n]*

identifier
  =  a:([a-z] / [A-Z] / "_") b:([a-z] / [A-Z] / [0-9] /"_")* {return a + b.join("");}

spaces
  =  [ \t\r\n]+ {return "";}

string
  =  "\"" ("\\" . / [^"])* "\""
  /  "'" ("\\" . / [^'])* "'"

any_char
  =  .

:

/**
 * This function does foo.
 * Call it with bar.  Yadda yadda "groo".
 */
function foo(x)
{
    ...
}

var s = " /* ... */ function notAFunction() {} ... ";

// function alsoNotAFunction() 
// { ... }

function withoutMultiLineComment() {
}

var t = ' /* ... */ function notAFunction() {} ... ';

/**
 * BAR!
 * Call it?
 */





            function doc_way_above(x, y, z) {
    ...
}

// function done(){};

start() :

{
   "foo": "/** * This function does foo. * Call it with bar. Yadda yadda \"groo\". */",
   "withoutMultiLineComment": null,
   "doc_way_above": "/** * BAR! * Call it? */"
}

, , (, this.id = function() { ... }), PEG.js (, ). , , , .

, !

+8

, , .

0

Source: https://habr.com/ru/post/1775883/


All Articles